我只是想用一种不同的方法来解决这个问题。如果更方便,您可以将模型直接绑定到原始或复杂类型的集合。这里有 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" />
}
学生.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
}