使用Razor在POST上使用Model.List为null

Rhy*_*hys 8 c# asp.net-mvc

我的看法:

@foreach(var item in Model.List)
{
  @Html.HiddenFor(model => item.UserId)
  @Html.HiddenFor(model => item.Name)
  @Html.HiddenFor(model => item.Age)

  @Html.CheckBoxFor(model => item.IsChecked, new { id = item.UserId })
  <label>@item.Name</label>
}
Run Code Online (Sandbox Code Playgroud)

我的控制器:

[HttpPost]
public ActionResult Create(MyModel Model)
{
..
Run Code Online (Sandbox Code Playgroud)

Model.List 一片空白?

列表填充正常GET.但是,on POST(此特定View是一个表单)Model.List为null.我尝试过使用HiddenFor帮助器,但还没有成功.

任何建议/答案都表示赞赏.谢谢.

Mar*_*ark 19

您需要使用for循环而不是foreach循环来进行数据绑定才能正确使用集合.

因此,不要执行foreach循环,而是将代码更改为以下内容:

@for (var i = 0; i < Model.List.Count(); i++)
{
  @Html.HiddenFor(model => Model.List[i].UserId)
  @Html.HiddenFor(model => Model.List[i].Name)
  @Html.HiddenFor(model => Model.List[i].Age)

  @Html.CheckBoxFor(model => Model.List[i].IsChecked, new { id = Model.List[i].UserId })
  <label>@Model.List[i].Name</label>
}
Run Code Online (Sandbox Code Playgroud)

这使得ModelBinder可以跟踪您尝试绑定的集合中项目的索引.

如果您在完成此操作后查看生成的HTML,您会注意到生成的输入控件将如下所示:

<input type="hidden" name="List[0].IsChecked" />
Run Code Online (Sandbox Code Playgroud)

这使模型绑定器能够知道列表中绑定的项目.