Home > Backend Development > C++ > How Can I Efficiently Bind Lists of Items to Views in MVC 4?

How Can I Efficiently Bind Lists of Items to Views in MVC 4?

DDD
Release: 2024-12-30 04:18:28
Original
609 people have browsed it

How Can I Efficiently Bind Lists of Items to Views in MVC 4?

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

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

The HttpPost action would receive the updated View Model:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template