Model.List is null on POST using Razor

后端 未结 1 1436
小蘑菇
小蘑菇 2021-01-12 01:17

My view:

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


        
相关标签:
1条回答
  • 2021-01-12 01:45

    You need to use a for loop instead of a foreach loop for data binding to work correctly with collections.

    So instead of doing a foreach loop, change your code to something like this:

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

    This enables the ModelBinder to track the index of the item in your collection you're trying to bind.

    If you look at the generated HTML when you have done this, you will notice that the generated input controls will look something like this:

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

    This enables the model binder to know to which item in the list, it is binding to.

    0 讨论(0)
提交回复
热议问题