Custom Model Binding for Lists in MVC 4
Binding a list of items (IList) to a view in MVC has been a common challenge for developers. While older solutions exist, MVC 4 introduces enhancements that simplify the process.
For scenarios where each item in the list requires its own form for data entry, consider structuring your ViewModel as follows:
public class MyViewModel { public List<Person> Persons{get;set;} }
In the View, within the BeginForm:
@model MyViewModel @for( int i = 0; i < Model.Persons.Count(); ++i) { @Html.HiddenFor(m => m.Persons[i].PersonId) @Html.EditorFor(m => m.Persons[i].FirstName) @Html.EditorFor(m => m.Persons[i].LastName) }
The HttpPost action would receive the updated View Model:
[HttpPost]public ViewResult(MyViewModel vm) { ... }
Note that on postback, only properties with corresponding inputs in the form will have values. This is because MVC's model binding looks for consecutive IDs and stops binding after encountering a gap. Therefore, it's important to ensure that all items in the list have valid IDs and no gaps in the form.
The above is the detailed content of How Can I Efficiently Bind Lists of Items to Views in MVC 4?. For more information, please follow other related articles on the PHP Chinese website!