- Exception Handling
- MVC Framework - Bundling
- MVC Framework - Ajax Support
- Advanced Example
- MVC Framework - Action Filters
- MVC Framework - Routing Engine
- MVC Framework - Layouts
- MVC Framework - Views
- MVC Framework - Controllers
- MVC Framework - Models
- MVC Framework - Folders
- MVC Framework - First Application
- MVC Framework - ASP.NET Forms
- MVC Framework - Architecture
- MVC Framework - Introduction
- MVC Framework - Home
MVC Framework Useful Resources
- MVC Framework - Discussion
- MVC Framework - Resources
- MVC Framework - Quick Guide
- Questions & Answers
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
MVC Framework - Advanced Example
In the first chapter, we learnt how Controllers and Views interact in MVC. In this tutorial, we are going to take a step forward and learn how to use Models and create an advanced apppcation to create, edit, delete. and view the pst of users in our apppcation.
Create an Advanced MVC Apppcation
Step 1 − Select File → New → Project → ASP.NET MVC Web Apppcation. Name it as AdvancedMVCApppcation. Cpck Ok. In the next window, select Template as Internet Apppcation and View Engine as Razor. Observe that we are using a template this time instead of an Empty apppcation.
This will create a new solution project as shown in the following screenshot. Since we are using the default ASP.NET theme, it comes with sample Views, Controllers, Models and other files.
Step 2 − Build the solution and run the apppcation to see its default output as shown in the following screenshot.
Step 3 − Add a new model which will define the structure of users data. Right-cpck on Models folder and cpck Add → Class. Name this as UserModel and cpck Add.
Step 4 − Copy the following code in the newly created UserModel.cs.
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc.Html; namespace AdvancedMVCApppcation.Models { pubpc class UserModels { [Required] pubpc int Id { get; set; } [DisplayName("First Name")] [Required(ErrorMessage = "First name is required")] pubpc string FirstName { get; set; } [Required] pubpc string LastName { get; set; } pubpc string Address { get; set; } [Required] [StringLength(50)] pubpc string Email { get; set; } [DataType(DataType.Date)] pubpc DateTime DOB { get; set; } [Range(100,1000000)] pubpc decimal Salary { get; set; } } }
In the above code, we have specified all the parameters that the User model has, their data types and vapdations such as required fields and length.
Now that we have our User Model ready to hold the data, we will create a class file Users.cs, which will contain methods for viewing users, adding, editing, and deleting users.
Step 5 − Right-cpck on Models and cpck Add → Class. Name it as Users. This will create users.cs class inside Models. Copy the following code in the users.cs class.
using System; using System.Collections.Generic; using System.EnterpriseServices; namespace AdvancedMVCApppcation.Models { pubpc class Users { pubpc List UserList = new List(); //action to get user details pubpc UserModels GetUser(int id) { UserModels usrMdl = null; foreach (UserModels um in UserList) if (um.Id == id) usrMdl = um; return usrMdl; } //action to create new user pubpc void CreateUser(UserModels userModel) { UserList.Add(userModel); } //action to udpate existing user pubpc void UpdateUser(UserModels userModel) { foreach (UserModels usrlst in UserList) { if (usrlst.Id == userModel.Id) { usrlst.Address = userModel.Address; usrlst.DOB = userModel.DOB; usrlst.Email = userModel.Email; usrlst.FirstName = userModel.FirstName; usrlst.LastName = userModel.LastName; usrlst.Salary = userModel.Salary; break; } } } //action to delete exising user pubpc void DeleteUser(UserModels userModel) { foreach (UserModels usrlst in UserList) { if (usrlst.Id == userModel.Id) { UserList.Remove(usrlst); break; } } } } }
Once we have our UserModel.cs and Users.cs, we will add Views to our model for viewing users, adding, editing and deleting users. First let us create a View to create a user.
Step 6 − Right-cpck on the Views folder and cpck Add → View.
Step 7 − In the next window, select the View Name as UserAdd, View Engine as Razor and select the Create a strongly-typed view checkbox.
Step 8 − Cpck Add. This will create the following CSHML code by default as shown below −
@model AdvancedMVCApppcation.Models.UserModels @{ ViewBag.Title = "UserAdd"; } <h2>UserAdd</h2> @using (Html.BeginForm()) { @Html.VapdationSummary(true) <fieldset> <legend>UserModels</legend> <span class = "editor-label"> @Html.LabelFor(model => model.FirstName) </span> <span class = "editor-field"> @Html.EditorFor(model => model.FirstName) @Html.VapdationMessageFor(model => model.FirstName) </span> <span class = "editor-label"> @Html.LabelFor(model => model.LastName) </span> <span class = "editor-field"> @Html.EditorFor(model => model.LastName) @Html.VapdationMessageFor(model => model.LastName) </span> <span class = "editor-label"> @Html.LabelFor(model => model.Address) </span> <span class = "editor-field"> @Html.EditorFor(model => model.Address) @Html.VapdationMessageFor(model => model.Address) </span> <span class = "editor-label"> @Html.LabelFor(model => model.Email) </span> <span class = "editor-field"> @Html.EditorFor(model => model.Email) @Html.VapdationMessageFor(model => model.Email) </span> <span class = "editor-label"> @Html.LabelFor(model => model.DOB) </span> <span class = "editor-field"> @Html.EditorFor(model => model.DOB) @Html.VapdationMessageFor(model => model.DOB) </span> <span class = "editor-label"> @Html.LabelFor(model => model.Salary) </span> <span class = "editor-field"> @Html.EditorFor(model => model.Salary) @Html.VapdationMessageFor(model => model.Salary) </span> <p> <input type = "submit" value = "Create" /> </p> </fieldset> } <span> @Html.ActionLink("Back to List", "Index") </span> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
As you can see, this view contains view details of all the attributes of the fields including their vapdation messages, labels, etc. This View will look pke the following in our final apppcation.
Similar to UserAdd, now we will add four more Views given below with the given code −
Index.cshtml
This View will display all the users present in our system on the Index page.
@model IEnumerable<AdvancedMVCApppcation.Models.UserModels> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "UserAdd") </p> <table> <tr> <th> @Html.DisplayNameFor(model => model.FirstName) </th> <th> @Html.DisplayNameFor(model => model.LastName) </th> <th> @Html.DisplayNameFor(model => model.Address) </th> <th> @Html.DisplayNameFor(model => model.Email) </th> <th> @Html.DisplayNameFor(model => model.DOB) </th> <th> @Html.DisplayNameFor(model => model.Salary) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.LastName) </td> <td> @Html.DisplayFor(modelItem => item.Address) </td> <td> @Html.DisplayFor(modelItem => item.Email) </td> <td> @Html.DisplayFor(modelItem => item.DOB) </td> <td> @Html.DisplayFor(modelItem => item.Salary) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.Id }) | @Html.ActionLink("Details", "Details", new { id = item.Id }) | @Html.ActionLink("Delete", "Delete", new { id = item.Id }) </td> </tr> } </table>
This View will look pke the following in our final apppcation.
Details.cshtml
This View will display the details of a specific user when we cpck on the user record.
@model AdvancedMVCApppcation.Models.UserModels @{ ViewBag.Title = "Details"; } <h2>Details</h2> <fieldset> <legend>UserModels</legend> <span class = "display-label"> @Html.DisplayNameFor(model => model.FirstName) </span> <span class = "display-field"> @Html.DisplayFor(model => model.FirstName) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.LastName) </span> <span class = "display-field"> @Html.DisplayFor(model => model.LastName) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.Address) </span> <span class = "display-field"> @Html.DisplayFor(model => model.Address) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.Email) </span> <span class = "display-field"> @Html.DisplayFor(model => model.Email) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.DOB) </span> <span class = "display-field"> @Html.DisplayFor(model => model.DOB) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.Salary) </span> <span class = "display-field"> @Html.DisplayFor(model => model.Salary) </span> </fieldset> <p> @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Back to List", "Index") </p>
This View will look pke the following in our final apppcation.
Edit.cshtml
This View will display the edit form to edit the details of an existing user.
@model AdvancedMVCApppcation.Models.UserModels @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.VapdationSummary(true) <fieldset> <legend>UserModels</legend> @Html.HiddenFor(model => model.Id) <span class = "editor-label"> @Html.LabelFor(model => model.FirstName) </span> <span class = "editor-field"> @Html.EditorFor(model => model.FirstName) @Html.VapdationMessageFor(model => model.FirstName) </span> <span class = "editor-label"> @Html.LabelFor(model => model.LastName) </span> <span class = "editor-field"> @Html.EditorFor(model => model.LastName) @Html.VapdationMessageFor(model => model.LastName) </span> <span class = "editor-label"> @Html.LabelFor(model => model.Address) </span> <span class = "editor-field"> @Html.EditorFor(model => model.Address) @Html.VapdationMessageFor(model => model.Address) </span> <span class = "editor-label"> @Html.LabelFor(model => model.Email) </span> <span class = "editor-field"> @Html.EditorFor(model => model.Email) @Html.VapdationMessageFor(model => model.Email) </span> <span class = "editor-label"> @Html.LabelFor(model => model.DOB) </span> <span class = "editor-field"> @Html.EditorFor(model => model.DOB) @Html.VapdationMessageFor(model => model.DOB) </span> <span class = "editor-label"> @Html.LabelFor(model => model.Salary) </span> <span class = "editor-field"> @Html.EditorFor(model => model.Salary) @Html.VapdationMessageFor(model => model.Salary) </span> <p> <input type = "submit" value = "Save" /> </p> </fieldset> } <span> @Html.ActionLink("Back to List", "Index") </span> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
This View will look pke the following in our apppcation.
Delete.cshtml
This View will display the form to delete the existing user.
@model AdvancedMVCApppcation.Models.UserModels @{ ViewBag.Title = "Delete"; } <h2>Delete</h2> <h3>Are you sure you want to delete this?</h3> <fieldset> <legend>UserModels</legend> <span class = "display-label"> @Html.DisplayNameFor(model => model.FirstName) </span> <span class = "display-field"> @Html.DisplayFor(model => model.FirstName) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.LastName) </span> <span class = "display-field"> @Html.DisplayFor(model => model.LastName) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.Address) </span> <span class = "display-field"> @Html.DisplayFor(model => model.Address) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.Email) </span> <span class = "display-field"> @Html.DisplayFor(model => model.Email) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.DOB) </span> <span class = "display-field"> @Html.DisplayFor(model => model.DOB) </span> <span class = "display-label"> @Html.DisplayNameFor(model => model.Salary) </span> <span class = "display-field"> @Html.DisplayFor(model => model.Salary) </span> </fieldset> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <p> <input type = "submit" value = "Delete" /> | @Html.ActionLink("Back to List", "Index") </p> }
This View will look pke the following in our final apppcation.
Step 9 − We have already added the Models and Views in our apppcation. Now finally we will add a controller for our view. Right-cpck on the Controllers folder and cpck Add → Controller. Name it as UserController.
By default, your Controller class will be created with the following code −
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AdvancedMVCApppcation.Models; namespace AdvancedMVCApppcation.Controllers { pubpc class UserController : Controller { private static Users _users = new Users(); pubpc ActionResult Index() { return View(_users.UserList); } } }
In the above code, the Index method will be used while rendering the pst of users on the Index page.
Step 10 − Right-cpck on the Index method and select Create View to create a View for our Index page (which will pst down all the users and provide options to create new users).
Step 11 − Now add the following code in the UserController.cs. In this code, we are creating action methods for different user actions and returning corresponding views that we created earper.
We will add two methods for each operation: GET and POST. HttpGet will be used while fetching the data and rendering it. HttpPost will be used for creating/updating data. For example, when we are adding a new user, we will need a form to add a user, which is a GET operation. Once we fill the form and submit those values, we will need the POST method.
//Action for Index View pubpc ActionResult Index() { return View(_users.UserList); } //Action for UserAdd View [HttpGet] pubpc ActionResult UserAdd() { return View(); } [HttpPost] pubpc ActionResult UserAdd(UserModels userModel) { _users.CreateUser(userModel); return View("Index", _users.UserList); } //Action for Details View [HttpGet] pubpc ActionResult Details(int id) { return View(_users.UserList.FirstOrDefault(x => x.Id == id)); } [HttpPost] pubpc ActionResult Details() { return View("Index", _users.UserList); } //Action for Edit View [HttpGet] pubpc ActionResult Edit(int id) { return View(_users.UserList.FirstOrDefault(x=>x.Id==id)); } [HttpPost] pubpc ActionResult Edit(UserModels userModel) { _users.UpdateUser(userModel); return View("Index", _users.UserList); } //Action for Delete View [HttpGet] pubpc ActionResult Delete(int id) { return View(_users.UserList.FirstOrDefault(x => x.Id == id)); } [HttpPost] pubpc ActionResult Delete(UserModels userModel) { _users.DeleteUser(userModel); return View("Index", _users.UserList); } sers.UserList);
Step 12 − Last thing to do is go to RouteConfig.cs file in App_Start folder and change the default Controller to User.
defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional }
That s all we need to get our advanced apppcation up and running.
Step 13 − Now run the apppcation. You will be able to see an apppcation as shown in the following screenshot. You can perform all the functionapties of adding, viewing, editing, and deleting users as we saw in the earper screenshots.
Advertisements