Home >Backend Development >C++ >How to Effectively Handle Model Binding with Lists in ASP.NET MVC 4?
When attempting to bind an IList of items to a view, issues can arise with the HttpPost method. While helpful resources like Phil Haack's article exist, they may not reflect the potential updates in MVC 4. To address this, let's explore a detailed solution.
public class MyViewModel { public List<Person> Persons{get;set;} }
@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) }
[HttpPost]public ViewResult(MyViewModel vm) { ... }
Note that only properties with input fields will have values after the postback. Additionally, MVC's model binding机制 only recognizes consecutive IDs. Consider this example where an item is conditionally hidden:
@for( int i = 0; i < Model.Persons.Count(); ++i) { if(i != 4)//conditionally hide 5th item, { //but BUG occurs on postback, all items after 5th will not be bound to the the list @Html.HiddenFor(m => m.Persons[i].PersonId) @Html.EditorFor(m => m.Persons[i].FirstName) @Html.EditorFor(m => m.Persons[i].LastName) } }
In this case, only the first four items will be bound on the postback. To avoid this, ensure consecutive IDs for all items in the IList.
The above is the detailed content of How to Effectively Handle Model Binding with Lists in ASP.NET MVC 4?. For more information, please follow other related articles on the PHP Chinese website!