如何通过&在索引和编辑视图中合并MVC3中的两个模型(强烈约束)?

时间:2011-10-21 07:12:06

标签: asp.net asp.net-mvc-3 asp.net-mvc-2 razor

模型/ Db实体关系(基线占位符文学内容):

public class TitlePercent
{
   public int TitleName; 
   public decimal Percentage;      
}

public class TitleMonthly
{
   public string Month;
   public int Val;
}

基数=> 1 TitlePercent to * TitleMonthly

Illustrated View(建议):

_____________________________
Name  | % ||  Jan | Feb |
_____________________________
Title1 2%     23    343
Title2 3%     343   3434
_____________________________

控制器(建议):

    // Need view and edit   
    public ViewResult ViewTitlePercentAndTitleMontly()
    {
        return View(db.<NotSureWhatWouldGoHere>.ToList());
    }

    public ActionResult EditTitlePercentAndTitleMontly(int id)
    {
        return View(db.<NotSureWhatWouldGoHere>.Find(id));
    }

Razor View(拟议的伪造): ...查看和编辑     @model MVC3.Models.TitlePercent     @ model2 MVC3.Models.TitleMonthly

1. For Index View to show the grid not sure how to mash this up (like the grid)
   - Perhaps build this in the controller but not sure how to build and pass that to the view as
     I have had not dealt with multiple models as relationships.
2. For Edit View need to figure out how to bind to a model similar to:
    @Html.EditorFor(model => model.TitleName)
    @Html.EditorFor(model => model.Percentage)

    foreach TitleMonthly in TitlePercentag
    {
       @* Iterate and bind somehow *@
       @Html.EditorFor(model2 => model2.Month)
       @Html.EditorFor(model2 => model2.Val)
    }
    ???

很抱歉缺少详细信息和伪代码,但我不必处理多个模型,特别是如果它们是彼此的相关/依赖关系,并且网格视图可以通过连接的类/表创建。 ...然后,如果你想编辑一行(两个类的组合,那么如何根据这两个类模型将所有关系绑定到文本框)?

同样,我会对此提出嘲笑,但任何信息和例子将不胜感激。

1 个答案:

答案 0 :(得分:3)

通常你会使用名为ViewModel的东西,这是一个为视图设计的非常具体的模型。您将使用数据模型中的信息填充该模型,然后将其传递给View。它不必具有1:1结构,这可以让您获得更多信息或更少信息,具体取决于您的需求。

对于您的编辑器模型,您可以创建类似于:

的ViewModel
public class TitleEditingViewModel { 
    public TitlePercent TitlePercent {get;set;}
    public ICollection<TitleMonthly> MonthlyTitles {get;set;}
}

然后,您可以在控制器中填充该模型,然后将模型传递到视图中。

@Html.EditorFor(model => model.TitlePercent.TitleName)
@Html.EditorFor(model => model.TitlePercent.Percentage)

@foreach titleMonthly in Model.MonthlyTitles {
   @Html.EditorFor(model => titleMonthly.Month)
   @Html.EditorFor(model => titleMonthly.Val)
}