I have trouble understanding how asp.net mvc model binders are working.
Models
public class Detail
{
public Guid Id { get; set; }
public string Title {get; set; }
}
public class Master
{
public Guid Id { get; set;}
public string Title { get; set; }
public List<Detail> Details { get; set; }
}
View
<!-- part of master view in ~/Views/Master/EditMaster.cshtml -->
@model Master
@using (Html.BeginForm())
{
@Html.HiddenFor(m => m.Id)
@Html.TextBoxFor(m => m.Title)
@Html.EditorFor(m => m.Details)
<!-- snip -->
}
<!-- detail view in ~/Views/Master/EditorTemplates/Detail.cshtml -->
@model Detail
@Html.HiddenFor(m => m.Id)
@Html.EditorFor(m => m.Title)
Controller
// Alternative 1 - the one that does not work
public ActionResult Save(Master master)
{
// master.Details not populated!
}
// Alternative 2 - one that do work
public ActionResult Save(Master master, [Bind(Prefix="Details")]IEnumerable<Detail> details)
{
// master.Details still not populated, but details parameter is.
}
Rendered html
<form action="..." method="post">
<input type="hidden" name="Id" value="....">
<input type="text" name="Title" value="master title">
<input type="hidden" name="Details[0].Id" value="....">
<input type="text" name="Details[0].Title value="detail title">
<input type="hidden" name="Details[1].Id" value="....">
<input type="text" name="Details[1].Title value="detail title">
<input type="hidden" name="Details[2].Id" value="....">
<input type="text" name="Details[2].Title value="detail title">
<input type="submit">
</form>
Why want the default model binder populate the Details-property on the model? Why do I have to include it as a separate parameter to the controller?
I have read multiple posts about asp and binding to lists, including Haackeds that is referred to multiple times in other questions. It was this thread on SO that lead me to the [Binding(Prefix...)]
option. It says that 'the model probably are too complex', but what exactly is 'too complex' for the default model binder to work with?