点击回发时出现以下错误:
传入字典的模型项的类型为“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中将为null,从而产生以下错误的语句:
@Html.Partial("_Attribute", null)
解决方案是使用HTML帮助程序“EditorFor”。看看Complex models and partial views - model binding issue in ASP.NET MVC 3
答案 0 :(得分:2)
我怀疑你的问题出在你的回发行动中。我认为它获取的视图AttributeModel
为null
所以当您调用Partial时,实际上是使用("_Attribute", null)
调用它,如果模型为null,那么它将通过相反,当前的模型。
您需要确保AttributeModel
上有效ProductsModel
。
答案 1 :(得分:1)
您需要初始化类的AttributeModel属性,如
public class ProductsModel
{
[Required]
public string Name { get; set; }
public AttributeModel AttributeModel { get; set; }
public ProductsModel()
{
this.AttributeModel =new AttributeModel();
}
}
因为最初AttributeModel属性设置为null。
答案 2 :(得分:0)
错误是非常具有描述性的。它告诉我做错了什么。
您的部分视图需要Test.Models.AttributeModel
类型的对象,但您要传递Test.Models.ProductsModel
类型的对象
您已将模型设置为Test.Models.AttributeModel
@model Test.Models.AttributeModel
<h2>_Attribute</h2>
@Html.ValidationMessageFor(m => m.Size)
@Html.TextBoxFor(m => m.Size)
将部分视图模型更改为Test.Models.AttributeModel
或从操作中传递Test.Models.AttributeModel
类型的对象。