My view:
@foreach(var item in Model.List)
{
@Html.HiddenFor(model => item.UserId)
@Html.HiddenFor(model => item.Name)
@Html.HiddenFor(model =>
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.