List binding demo

Model binding in ASP.NET Core can correctly map form data to lists of objects.
When dealing with collections, form fields must follow an indexed naming pattern like `Items[0].Name`, `Items[1].Name`, etc. This ensures ASP.NET correctly associates each input with the corresponding list item. Missing indices can cause binding issues, so maintaining sequential numbering is important. Using loops in views simplifies generating indexed fields dynamically, and hidden inputs help retain existing data when editing lists.
This approach is useful for dynamic forms, data grids, or any scenario requiring user input for multiple items at once.
Related article: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/





 

  •  



 

  •  



 

  •  


ListBinding/Index.cshtml
@using (Html.BeginForm())
{
<table class="tt">
@for (var j = 0; j < Model.Dinners.Count(); j++)
{
var i = j;
<tr>
<td>
@Html.HiddenFor(o => o.Dinners[i].Id)
@Html.Awe().TextBoxFor(o => o.Dinners[i].Name).Value(Model.Dinners[i].Name)
@Html.ValidationMessageFor(o => o.Dinners[i].Name)
<br />
</td>
<td>
@Html.Awe().DatePickerFor(o => o.Dinners[i].Date).Value(Model.Dinners[i].Date).ClearButton()<br />
@Html.ValidationMessageFor(o => o.Dinners[i].Date)
</td>
<td>
@Html.Awe().LookupFor(o => o.Dinners[i].ChefId).Controller("ChefLookup").Value(Model.Dinners[i].ChefId).ClearButton()<br />
@Html.ValidationMessageFor(o => o.Dinners[i].ChefId)
</td>
<td>
@Html.Awe().MultiLookupFor(o => o.Dinners[i].MealsIds).Controller("MealsMultiLookup").Value(Model.Dinners[i].MealsIds).ClearButton()<br />
@Html.ValidationMessageFor(o => o.Dinners[i].MealsIds)
</td>
</tr>

}
</table>
<br/>
@Html.AntiForgeryToken()
<input type="submit" value="submit" class="awe-btn"/>
}



Comments