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.
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.
Then add the view for that method.
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.
We have to modify the view to include the input fields to get the data from end user.
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.
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.
Now we can fill the books detail in front end and then click on the submit the form.
In the debug mode you can see entered data are available as a Book list ?
You can use the books list as you wish. This is how model data bind object list works in ASP .NET MVC.