Я просто хочу присоединиться к другому подходу, который вы можете использовать для этого. Если это более удобно, вы можете связать модель напрямую с коллекциями примитивных или сложных типов. Вот 2 примера:
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>
}
Первая форма просто связывает список строк. Второе, связывает данные формы с List<Student>
. Используя этот подход, вы можете позволить связующему с моделью по умолчанию выполнить утомительную работу за вас.
Обновлено для комментария
Да, вы тоже можете это сделать:
Форма:
@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" />
}
Действие контроллера:
public ActionResult ListComplexModel(List<Student> items, int ClassId)
{
// do stuff
}