Home > Backend Development > C++ > How to Effectively Handle Model Binding with Lists in ASP.NET MVC 4?

How to Effectively Handle Model Binding with Lists in ASP.NET MVC 4?

Susan Sarandon
Release: 2025-01-03 09:32:39
Original
729 people have browsed it

How to Effectively Handle Model Binding with Lists in ASP.NET MVC 4?

Model Binding to a List in 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.

ViewModel Configuration

public class MyViewModel
{
   public List<Person> Persons{get;set;}
}
Copy after login

View Implementation

@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)         
}
Copy after login

Action Method

[HttpPost]public ViewResult(MyViewModel vm)
{
...
}
Copy after login

Considerations

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)           
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template