Reputation: 2183
My view:
@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>
}
My controller:
[HttpPost]
public ActionResult Create(MyModel Model)
{
..
Model.List
is null?
The list populates okay on GET
. However, on POST
(this particular View is a form) Model.List
is null. I've tried using the HiddenFor
helper, but have not yet succeeded.
Any suggestions / answers are appreciated. Thanks.
Upvotes: 11
Views: 10780
Reputation: 1748
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.
Upvotes: 27