I get the following error when I hit the postback:
The model element passed to the dictionary is of type "Test.Models.ProductsModel", but for this dictionary a model element of type "Test.Models.AttributeModel" is required
What I want to achieve, hopefully, will be pretty self-evident with the code below
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)
controller
[HttpGet]
public ActionResult Create()
{
ProductsModel model = new ProductsModel { AttributeModel = new AttributeModel() };
return View(model);
}
[HttpPost]
public ActionResult Create(ProductsModel m)
{
return View(m);
}
EDITING - SOLUTION
I found that the problem occurs because no input is associated with the AttributeModel, which means that it will be null in the ProductsModel, which will result in the following erronomic statement:
@Html.Partial("_Attribute", null)
HTML- "EditorFor". - ASP.NET MVC 3