模型.列表是空的POST使用剃刀

本文关键字:剃刀 POST 列表 模型 | 更新日期: 2023-09-27 18:16:34

我的观点:

@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>
}

我的控制器:

[HttpPost]
public ActionResult Create(MyModel Model)
{
..

Model.List为空?

列表在GET上填充得很好。然而,在POST(这个特定的视图是一个形式)上,Model.List是空的。我已经尝试使用HiddenFor助手,但尚未成功。

任何建议/答案都是赞赏的。谢谢。

模型.列表是空的POST使用剃刀

您需要使用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>
}

这使ModelBinder能够跟踪您试图绑定的集合中项目的索引。

如果您查看生成的HTML,您会注意到生成的输入控件看起来像这样:

<input type="hidden" name="List[0].IsChecked" />

这使模型绑定器能够知道它绑定到列表中的哪个项。