asp.net - 如何在索引和编辑 View (强绑定(bind))中传递和合并 MVC3 中的两个模型?

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

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

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

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

基数 => 1 TitlePercent 至 * TitleMonthly

插图 View (建议):

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

Controller (建议):

    // 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)
    }
    ???

抱歉缺少细节和伪代码,但我只是不必处理多个模型,特别是如果它们彼此相关/依赖,并且其中可以通过连接的类/表创建 GridView 。 ...那么如果您想编辑一行(两个类的组合,那么如何将所有关系绑定(bind)到基于这两个类模型的文本框)?

再次,我将对此进行 mock ,但任何信息和示例将不胜感激。

最佳答案

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

对于您的编辑器模型,您可以创建一个类似于以下内容的 ViewModel:

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

然后,您可以根据需要在 Controller 中填充该模型,然后将模型传递到 View 中。

@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)
}

关于asp.net - 如何在索引和编辑 View (强绑定(bind))中传递和合并 MVC3 中的两个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7846113/

相关文章:

c# - 将通用参数传递给 MVC Action

asp.net-mvc - 将用户对象传递给 Controller ​​操作会导致很大的延迟

asp.net-mvc - Knockout.js 和复选框列表 : post to mvc controller

asp.net-mvc - 一个 ASP.NET MVC 验证器,用于确保至少选中一个复选框

asp.net - Web.config 更改后程序集不可用

c# - 在 C# 中通过 System.DirectoryServices 查询自定义 LDAP 属性?

javascript - 如何从 aspx 页面引用 jquery 函数?

c# - MVC3 如何检查 HttpPostedFileBase 是否是图像

json - 更多 Ajax/MVC 怪异之处

asp.net - 在网站上放置广告的最佳做法是什么?