当我点击postback时,出现以下错误:
字典中传递的模型项目类型为“Test.Models.ProductsModel”,但该字典需要一个模型项目类型为“Test.Models.AttributeModel”
我的目标很明显,就是通过下面的代码实现。
public class ProductsModel
{
[Required]
public string Name { get; set; }
public AttributeModel AttributeModel { get; set; }
}
public class AttributeModel
{
[Required]
public int Size { get; set; }
}
Create.cshtml
@model Test.Models.ProductsModel
@using (Html.BeginForm()) {
@Html.ValidationMessageFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.Partial("_Attribute", Model.AttributeModel)
<input type="submit" value="Click me" />
}
_Attribute.cshtml
@model Test.Models.AttributeModel
<h2>_Attribute</h2>
@Html.ValidationMessageFor(m => m.Size)
@Html.TextBoxFor(m => m.Size)
控制器
[HttpGet]
public ActionResult Create()
{
ProductsModel model = new ProductsModel { AttributeModel = new AttributeModel() };
return View(model);
}
[HttpPost]
public ActionResult Create(ProductsModel m)
{
return View(m);
}
编辑 - 解决方案
我发现该问题是因为没有将输入绑定到AttributeModel,这意味着在ProductsModel中它将为空,导致以下错误语句:
@Html.Partial("_Attribute", null)
解决方案是使用HTML助手“EditorFor”。请参考ASP.NET MVC 3中复杂模型和部分视图的模型绑定问题