Home > Backend Development > C++ > How Can I Effectively Bind a List to a View in ASP.NET MVC 4 During HttpPost?

How Can I Effectively Bind a List to a View in ASP.NET MVC 4 During HttpPost?

Barbara Streisand
Release: 2024-12-27 21:03:13
Original
937 people have browsed it

How Can I Effectively Bind a List to a View in ASP.NET MVC 4 During HttpPost?

Model Binding to a List in MVC 4

When attempting to bind an IList of items to a view in MVC 4, issues can arise during HttpPost. To address this challenge, consider the following pattern:

ViewModel:

Create a ViewModel that contains the IList of items:

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

View:

In the view, iterate over the IList and generate form inputs for each property:

@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:

In the action method, handle the posted MyViewModel object:

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

Considerations:

  • Only properties with corresponding inputs in the view will have values on HttpPost.
  • MVC's model binding only works for consecutive IDs. If you conditionally hide items, data may not be bound correctly.
  • To solve the issue of gaps in IDs, consider using this solution:
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    @Html.Hidden($"Persons[{i}].PersonId", Model.Persons[i].PersonId)
    @Html.Editor($"Persons[{i}].FirstName", Model.Persons[i].FirstName) 
    @Html.Editor($"Persons[{i}].LastName", Model.Persons[i].LastName)           
}
Copy after login

The above is the detailed content of How Can I Effectively Bind a List to a View in ASP.NET MVC 4 During HttpPost?. 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