复杂模型和部分视图 – ASP.NET MVC 3中的模型绑定问题

我在示例MVC 3应用程序, SimpleModelComplexModel有2个模型,如下所示:

 public class SimpleModel { public string Status { get; set; } } public class ComplexModel { public ComplexModel() { Simple = new SimpleModel(); } public SimpleModel Simple{ get; set; } } 

我已经为这个模型定义了视图:

_SimplePartial.cshtml

 @model SimpleModel @Html.LabelFor(model => model.Status) @Html.EditorFor(model => model.Status) 

Complex.cshtml

 @model ComplexModel @using (Html.BeginForm()) { @Html.Partial("_SimplePartial", Model.Simple) <input type="submit" value="Save" /> } 

提交表单后,在“ Status字段中input随机值,该值不绑定到我的模型。 当我在控制器操作中检查模型时, Status字段为NULL

 [HttpPost] public ActionResult Complex(ComplexModel model) { // model.Simple.Status is NULL, why ? } 

为什么不绑定? 我不想inheritance模型。 我是否必须为这种简单的情况编写自定义模型粘合剂?

问候。

代替:

 @Html.Partial("_SimplePartial", Model.Simple) 

我会build议你使用编辑器模板:

 @model ComplexModel @using (Html.BeginForm()) { @Html.EditorFor(x => x.Simple) <input type="submit" value="Save" /> } 

然后把简单的部分里面~/Views/Shared/EditorTemplates/SimpleModel.cshtml或里面~/Views/Home/EditorTemplates/SimpleModel.cshtml其中Home是您的控制器的名称:

 @model SimpleModel @Html.LabelFor(model => model.Status) @Html.EditorFor(model => model.Status) 

当然,如果你喜欢在某个特定的位置上拥有这个部分,而不遵循这个约定(你为什么这么做?),你可以指定位置:

 @Html.EditorFor(x => x.Simple, "~/Views/SomeUnexpectedLocation/_SimplePartial.cshtml") 

那么一切都会如预期的那样到位。

正如Daniel Hall在他的博客中所build议的那样 ,将一个ViewDataDictionary与一个TemplateInfo一起传递,其中HtmlFieldPrefix被设置为SimpleModel属性的名字:

  @Html.Partial("_SimplePartial", Model.Simple, new ViewDataDictionary(ViewData) { TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "Simple" } })