I get the following error when I hit the postback:
The model item passed into the dictionary is of type 'Test.Models.ProductsModel', but this dictionary requires a model item of type 'Test.Models.AttributeModel'
What I want to achieve is hopefully pretty selfexplanatory 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);
}
EDIT - SOLUTION
I found that the problem occurs because no input binds to AttributeModel which means that it will be null in ProductsModel, resulting in the follow errouneous statement:
@Html.Partial("_Attribute", null)
The solution is to use the HTML helper "EditorFor". Have a look at Complex models and partial views - model binding issue in ASP.NET MVC 3