Simple Way of Binding List of Objects to View using MVC
Introduction
I would like to show list of users on HTML page using MVC. I am assuming you are aware from MVC.
Following would be Steps
1) Adding Model
We have added UserModel.cs inside Models folder.
It has username, age and Gender as properties. Various attributes has been defined for validations
2) Adding Controller.
Using Right click on controller folder and we added UserController.cs.
We have added UserContoller.cs inside Controller folder and Created DisplaUserDetails() Method. Inside this method we created a list of users and passed to view.
Here list of users basically are the list of UserModel
List<UserModel> listuser = new List<UserModel>();
UserModel users = new UserModel();
users.UserName = "Devesh Omar";
users.Age = 12;
users.Gender = "M";
listuser.Add(users);
users = new UserModel();
users.UserName = "Ram Kumar";
users.Age = 12;
users.Gender = "M";
listuser.Add(users);
return View(listuser); // here we are passing data to view.
Here in last line we are passing List of users to View using View(listuser), because our aim is to display list of users at View page.
3) Adding View
a) Right Click on DisplayUserDetails() and Click on Add View..
b) After clicking on Add View We will get following screen.
· Select Checkbox ”Strongly-typed view”
· Select “UserModel” from View Data class dropdown
· Select “List” from View content dropDown.
· Then click on Add button.
4) Now after step 3, we will have strongly typed View, having name = DisplayUserDetails.aspx
5) Here in MVC arch we do not have any code – behind file.
6) Folder having name “User” automatically created.
We have folder having name = User because we created Controller having name= UserController.
7) Modifying Global.asax
We have some default settings at Global.asax file; we need to modify it to following code.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "User", action = "DisplayUserDetails", id = UrlParameter.Optional } // Parameter defaults
);
}
Following are modifications.
a) action = "DisplayUserDetails"
b) controller = "User"
8) Running the application and following would be output.
Conclusion
It is very simple way to bind data from model to view.
Inside code of controller we can modify the code as per our requirements like we can have database call and then we can fill list of users from data base. Then we can pass list of users to view for display.
Leave Comment