I\'ve been stuck a long time to edit a subcollection of my model, the collection of the model was coming null.
I finally found a solution, but I find it a little dir
You can simplify your code by introducing the EditorTemplate. Here is how:
TestForm.cshtml
@model WebTestApplication.Models.ContainerObject
@{
ViewBag.Title = "TestForm";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("TestFormResult", "Home", FormMethod.Post)) {
@Html.EditorFor(m => m.Title)
@Html.EditorFor(m => m.ObjectList);
<input type="submit" value="Submit" />
}
ContainedObject.cshtml
@model WebTestApplication.Models.ContainedObject
<p>
@Html.DisplayFor(m => m.Text)
@Html.CheckBoxFor(m => m.IsSelected)
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.Text)
</p>
The editor will automatically iterate through the list of objects rendering the view for each of them. Hope it helps.
I found this thread while looking for something else related. Denis has the correct answer, but I thought I would add some syntax in case anyone else comes across this:
If you have an editor template named "SomeTemplate.cshtml" you can use it for a list of Item as follows in your view:
@for (var i = 0; i < Model.ObjectList.Count(); i++)
{
@Html.EditorFor(m => m.ObjectList[i], "SomeTemplate")
}
Then in your editor template:
@model WebTestApplication.Models.ContainedObject
<br />
@Html.Label(Model.Text);
@Html.CheckBoxFor(m => m.IsSelected);
@Html.HiddenFor(m => m.Id);
@Html.HiddenFor(m => m.Text);