MVC Model Data Binding with Lists

ASP .NET model data binding with object lists

In this example we are going to retrieve a list of objects from the front end to controller.

We know how to bind a single object into the form and retrieve object data in form submission. Its very simple and we can accomplish that using the DefaultModelBinder in ASP.NET MVC. But when it comes to a complex data list its not that simple. Then how model data bind object list works in ASP .NET MVC ?

Lets say we are allowing the end user to enter their favorite x number of books as in the below image

The challenge is how to retrieve a list of objects from the front end to back end specially when the of object count is dynamic.

front

In here I’m using only 3 objects but we can use this concept for dynamically generated list too.

First add the controller method to load the view.

Get action

Then add the view for that method.

Add view

Add a class for Book list. In here we add a class called book and we use it in a list. Book has 3 properties Name, Author and Price.

book class

We have to modify the view to include the input fields to get the data from end user.

View

Inside the form we can add the input boxes to get the user inputs. Here we have to use some special pattern to name the inputs.

Note that the input fields are named using an indexing method. When you run the project and inspect this page with Developer Tools you can see how the input names are rendered in to the HTML page. using the for loop we are generating the input names dynamically based on an index number.

HTML

This index should be a zero based and unbroken sequence of integer numbers.

The code is basically generating names for the text boxes matching the following convention:

Books[n].[Model _Property_Name]

And in the controller we should define the parameter to match the Name in the view as shown below. In the View we defined input names as “Books[n].Property_Name” so the parameter in the post method should be “Books”. Then the model binder will do the rest for you.

post action

Now we can fill the books detail in front end and then click on the submit the form.

submit

In the debug mode you can see entered data are available as a Book list ?

debug

You can use the books list as you wish. This is how model data bind object list works in ASP .NET MVC.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.