I just want to call back with a different approach that you can use to do this. If this is more convenient, you can model the binding directly to collections of primitive or complex types. Here are two examples:
index.cshtml:
@using (Html.BeginForm("ListStrings", "Home")) { <p>Bind a collection of strings:</p> <input type="text" name="[0]" value="The quick" /><br /> <input type="text" name="[1]" value="brown fox" /><br /> <input type="text" name="[2]" value="jumped over" /><br /> <input type="text" name="[3]" value="the donkey" /><br /> <input type="submit" value="List" /> } @using (Html.BeginForm("ListComplexModel", "Home")) { <p>Bind a collection of complex models:</p> <input type="text" name="[0].Id" value="1" /><br /> <input type="text" name="[0].Name" value="Bob" /><br /> <input type="text" name="[1].Id" value="2" /><br /> <input type="text" name="[1].Name" value="Jane" /><br /> <input type="submit" value="List" /> }
Student.cs:
public class Student { public int Id { get; set; } public string Name { get; set; } }
HomeController.cs:
public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult ListStrings(List<string> items) { return View(items); } public ActionResult ListComplexModel(List<Student> items) { return View(items); } }
ListStrings.cshtml:
@foreach (var item in Model) { <p>@item</p> }
ListComplexModel.cshtml:
@foreach (var item in Model) { <p>@item.Id. @item.Name</p> }
The first form simply links the list of strings. The second, binds the form data to the List<Student> . Using this approach, you can let the default model binding do some tedious work for you.
Updated for comments
Yes, you can do this too:
the form:
@using (Html.BeginForm("ListComplexModel", "Home")) { <p>Bind a collection of complex models:</p> <input type="text" name="[0].Id" value="1" /><br /> <input type="text" name="[0].Name" value="Bob" /><br /> <input type="text" name="[1].Id" value="2" /><br /> <input type="text" name="[1].Name" value="Jane" /><br /> <input type="text" name="ClassId" value="13" /><br /> <input type="submit" value="List" /> }
Controller action:
public ActionResult ListComplexModel(List<Student> items, int ClassId) {
source share