簡體   English   中英

使用Razor的POST上Model.List為null

[英]Model.List is null on POST using Razor

我的看法:

@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 (此特定的View是一種表單)上, Model.List為null。 我曾嘗試使用HiddenFor幫助器,但尚未成功。

任何建議/答案表示贊賞。 謝謝。

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

這使模型綁定程序可以知道列表綁定到的項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM