I would like to show a list of users in a HTML page using MVC. I am assuming you are aware of MVC.
Use the following procedure to create a sample of that.
1. Adding Model
We have added the file UserModel.cs in the Models folder.
It has username, age and Gender as properties. The various attributes have been defined for validations.
Use the following procedure to create a sample of that.
1. Adding Model
We have added the file UserModel.cs in the Models folder.
It has username, age and Gender as properties. The various attributes have been defined for validations.
Right-click on the controller folder and add UserController.cs.
We have added the file UserContoller.cs inside the Controller folder and the Created DisplaUserDetails() Method. Inside this method we created a list of users and passed it to the view.
Here is a list of users that basically is the list of UserModels:
- 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.
3. Adding View
a. Right-click on DisplayUserDetails() and click on "Add View":
b. After clicking on "Add View" we will get the following screen.
- Select the Checkbox "Strongly-typed view"
- Select "UserModel" from the View Data class dropdown
- Select "List" from the View content dropDown.
- Then click on the "Add" button.
4. Now after Step 3, we will have a strongly typed View, with the name DisplayUserDetails.aspx.
5. Here in the MVC architecture we do not have any code – behind file.
6. The folder having the name "User" is automatically created.
We have the folder with the name User because we created the Controller with the name UserController.
7. Modifying Global.asax
We have some default settings of the Global.asax file; we need to modify it as in the 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
- );
- }
a. action = "DisplayUserDetails"
b. controller = "User"
8. Ececution
b. controller = "User"
8. Ececution
Run the application and the following will be the output:
No comments:
Post a Comment