Home > Backend Development > C++ > How to Bind an IList to a View in MVC 4?

How to Bind an IList to a View in MVC 4?

Patricia Arquette
Release: 2025-01-02 20:14:38
Original
467 people have browsed it

How to Bind an IList to a View in MVC 4?

Bind to a List in MVC 4

Binding an IList to a view in MVC 4 can be achieved through the following steps:

Define a ViewModel with a List property:

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

In the View, create a form and iterate through the list to render input fields:

@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

In the Action, receive the posted ViewModel:

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

Note that only properties with inputs in the form will be populated in the postback. If properties are conditionally hidden, gaps in the ID sequence will cause binding issues for subsequent items.

The above is the detailed content of How to Bind an IList to a View 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template