Consider the following data classes:
class TopLevel
{
public TopLevel()
{
collection = new Item[3];
}
public string Name { get; set; }
public Item[] collection { get; set; }
}
class Item
{
public string Name { get; set; }
public string Value { get; set; }
}
I made an Editor Template for Item:
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Value)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Value)
@Html.ValidationMessageFor(model => model.Value)
</div>
My create csthml for TopLevel looks like this:
@using(Html.BeginForm())
{
@Html.LabelFor( m => m.Name )
@Html.EditorFor( m => m.Name )
@Html.ValidationMessageFor( m => m.Name )
for (int i = 0; i < Model.Collection.Count(); i++)
{
@Html.EditorFor(m => m.Collection[i])
}
<input type="submit" value="Submit"/>
}
But in my controller
[HttpPost]
public ActionResult Create( TopLevel tl )
{
//tl.Collection contains three null Items.
}
The Item’s that make up Collection in my TopLevel class do not get created. Is there a way to accomplish this?
See this article for a solution. The magic is contained in the
using(Html.BeginCollectionItem("..."))block.