MVC Framework – Advanced Example ”; Previous Next 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 application to create, edit, delete. and view the list of users in our application. Create an Advanced MVC Application Step 1 − Select File → New → Project → ASP.NET MVC Web Application. Name it as AdvancedMVCApplication. Click Ok. In the next window, select Template as Internet Application and View Engine as Razor. Observe that we are using a template this time instead of an Empty application. 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 application 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-click on Models folder and click Add → Class. Name this as UserModel and click 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 AdvancedMVCApplication.Models { public class UserModels { [Required] public int Id { get; set; } [DisplayName(“First Name”)] [Required(ErrorMessage = “First name is required”)] public string FirstName { get; set; } [Required] public string LastName { get; set; } public string Address { get; set; } [Required] [StringLength(50)] public string Email { get; set; } [DataType(DataType.Date)] public DateTime DOB { get; set; } [Range(100,1000000)] public decimal Salary { get; set; } } } In the above code, we have specified all the parameters that the User model has, their data types and validations 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-click on Models and click 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 AdvancedMVCApplication.Models { public class Users { public List UserList = new List(); //action to get user details public 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 public void CreateUser(UserModels userModel) { UserList.Add(userModel); } //action to udpate existing user public 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 public 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-click on the Views folder and click 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 − Click Add. This will create the following CSHML code by default as shown below − @model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = “UserAdd”; } <h2>UserAdd</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserModels</legend> <div class = “editor-label”> @Html.LabelFor(model => model.FirstName) </div> <div class = “editor-field”> @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> <div class = “editor-label”> @Html.LabelFor(model => model.LastName) </div> <div class = “editor-field”> @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div> <div class = “editor-label”> @Html.LabelFor(model => model.Address) </div> <div class = “editor-field”> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <div class = “editor-label”> @Html.LabelFor(model => model.Email) </div> <div class = “editor-field”> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class = “editor-label”> @Html.LabelFor(model => model.DOB) </div> <div class = “editor-field”> @Html.EditorFor(model => model.DOB) @Html.ValidationMessageFor(model => model.DOB) </div> <div class = “editor-label”> @Html.LabelFor(model => model.Salary) </div> <div class = “editor-field”> @Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary) </div> <p> <input type = “submit” value = “Create” /> </p> </fieldset> } <div> @Html.ActionLink(“Back to List”, “Index”) </div> @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) } As you can see, this view contains view details of all the attributes of the fields including their validation messages, labels, etc. This View will look like the following in our final application. 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<AdvancedMVCApplication.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 like the following in our final application. Details.cshtml This View will display the details of a specific user when we click on the user record. @model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = “Details”; } <h2>Details</h2> <fieldset> <legend>UserModels</legend> <div class = “display-label”> @Html.DisplayNameFor(model => model.FirstName) </div> <div class = “display-field”> @Html.DisplayFor(model => model.FirstName) </div> <div class = “display-label”> @Html.DisplayNameFor(model => model.LastName) </div> <div class = “display-field”> @Html.DisplayFor(model => model.LastName) </div> <div class =
Category: mvc Framework
MVC Framework – Controllers
MVC Framework – Controllers ”; Previous Next Asp.net MVC Controllers are responsible for controlling the flow of the application execution. When you make a request (means request a page) to MVC application, a controller is responsible for returning the response to that request. The controller can perform one or more actions. The controller action can return different types of action results to a particular request. The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controller receives an input from the users via the View, then processes the user”s data with the help of Model and passes the results back to the View. Create a Controller To create a Controller − Step 1 − Create an MVC Empty Application and then right-click on the Controller folder in your MVC application. Step 2 − Select the menu option Add → Controller. After selection, the Add Controller dialog is displayed. Name the Controller as DemoController. A Controller class file will be created as shown in the following screenshot. Create a Controller with IController In the MVC Framework, controller classes must implement the IController interface from the System.Web.Mvc namespace. public interface IController { void Execute(RequestContext requestContext); } This is a very simple interface. The sole method, Execute, is invoked when a request is targeted at the controller class. The MVC Framework knows which controller class has been targeted in a request by reading the value of the controller property generated by the routing data. Step 1 − Add a new class file and name it as DemoCustomController. Now modify this class to inherit IController interface. Step 2 − Copy the following code inside this class. public class DemoCustomController:IController { public void Execute(System.Web.Routing.RequestContext requestContext) { var controller = (string)requestContext.RouteData.Values[“controller”]; var action = (string)requestContext.RouteData.Values[“action”]; requestContext.HttpContext.Response.Write( string.Format(“Controller: {0}, Action: {1}”, controller, action)); } } Step 3 − Run the application and you will receive the following output. Print Page Previous Next Advertisements ”;
MVC Framework – Discussion
Discuss MVC Framework ”; Previous Next As per the official definition, Model-View-Controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. Print Page Previous Next Advertisements ”;
Exception Handling
MVC Framework – Exception Handling ”; Previous Next In ASP.NET, error handling is done using the standard try catch approach or using application events. ASP.NET MVC comes with built-in support for exception handling using a feature known as exception filters. We are going to learn two approaches here: one with overriding the onException method and another by defining the HandleError filters. Override OnException Method This approach is used when we want to handle all the exceptions across the Action methods at the controller level. To understand this approach, create an MVC application (follow the steps covered in previous chapters). Now add a new Controller class and add the following code which overrides the onException method and explicitly throws an error in our Action method − Now let us create a common View named Error which will be shown to the user when any exception happens in the application. Inside the Views folder, create a new folder called Shared and add a new View named Error. Copy the following code inside the newly created Error.cshtml − If you try to run the application now, it will give the following result. The above code renders the Error View when any exception occurs in any of the action methods within this controller. The advantage of this approach is that multiple actions within the same controller can share this error handling logic. However, the disadvantage is that we cannot use the same error handling logic across multiple controllers. HandleError Attribute The HandleError Attribute is one of the action filters that we studied in Filters and Action Filters chapter. The HandleErrorAttribute is the default implementation of IExceptionFilter. This filter handles all the exceptions raised by controller actions, filters, and views. To use this feature, first of all turn on the customErrors section in web.config. Open the web.config and place the following code inside system.web and set its value as On. <customErrors mode = “On”/> We already have the Error View created inside the Shared folder under Views. This time change the code of this View file to the following, to strongly-type it with the HandleErrorInfo model (which is present under System.Web.MVC). @model System.Web.Mvc.HandleErrorInfo @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name = “viewport” content = “width = device-width” /> <title>Error</title> </head> <body> <h2> Sorry, an error occurred while processing your request. </h2> <h2>Exception details</h2> <p> Controller: @Model.ControllerName <br> Action: @Model.ActionName Exception: @Model.Exception </p> </body> </html> Now place the following code in your controller file which specifies [HandleError] attribute at the Controller file. using System; using System.Data.Common; using System.Web.Mvc; namespace ExceptionHandlingMVC.Controllers { [HandleError] public class ExceptionHandlingController : Controller { public ActionResult TestMethod() { throw new Exception(“Test Exception”); return View(); } } } If you try to run the application now, you will get an error similar to shown in the following screenshot. As you can see, this time the error contains more information about the Controller and Action related details. In this manner, the HandleError can be used at any level and across controllers to handle such errors. Print Page Previous Next Advertisements ”;
MVC Framework – Folders
MVC Framework – Folders ”; Previous Next Now that we have already created a sample MVC application, let us understand the folder structure of an MVC project. We will create new a MVC project to learn this. In your Visual Studio, open File → New → Project and select ASP.NET MVC Application. Name it as MVCFolderDemo. Click OK. In the next window, select Internet Application as the Project Template and click OK. This will create a sample MVC application as shown in the following screenshot. Note − Files present in this project are coming out of the default template that we have selected. These may change slightly as per different versions. Controllers Folder This folder will contain all the Controller classes. MVC requires the name of all the controller files to end with Controller. In our example, the Controllers folder contains two class files: AccountController and HomeController. Models Folder This folder will contain all the Model classes, which are used to work on application data. In our example, the Models folder contains AccountModels. You can open and look at the code in this file to see how the data model is created for managing accounts in our example. Views Folder This folder stores the HTML files related to application display and user interface. It contains one folder for each controller. In our example, you will see three sub-folders under Views, namely Account, Home and Shared which contains html files specific to that view area. App_Start Folder This folder contains all the files which are needed during the application load. For e.g., the RouteConfig file is used to route the incoming URL to the correct Controller and Action. Content Folder This folder contains all the static files, such as css, images, icons, etc. The Site.css file inside this folder is the default styling that the application applies. Scripts Folder This folder stores all the JS files in the project. By default, Visual Studio adds MVC, jQuery and other standard JS libraries. Print Page Previous Next Advertisements ”;
MVC Framework – Models
MVC Framework – Models ”; Previous Next The component ‘Model’ is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself. Model classes can either be created manually or generated from database entities. We are going to see a lot of examples for manually creating Models in the coming chapters. Thus in this chapter, we will try the other option, i.e. generating from the database so that you have hands-on experience on both the methods. Create Database Entities Connect to SQL Server and create a new database. Now run the following queries to create new tables. CREATE TABLE [dbo].[Student]( [StudentID] INT IDENTITY (1,1) NOT NULL, [LastName] NVARCHAR (50) NULL, [FirstName] NVARCHAR (50) NULL, [EnrollmentDate] DATETIME NULL, PRIMARY KEY CLUSTERED ([StudentID] ASC) ) CREATE TABLE [dbo].[Course]( [CourseID] INT IDENTITY (1,1) NOT NULL, [Title] NVARCHAR (50) NULL, [Credits] INT NULL, PRIMARY KEY CLUSTERED ([CourseID] ASC) ) CREATE TABLE [dbo].[Enrollment]( [EnrollmentID] INT IDENTITY (1,1) NOT NULL, [Grade] DECIMAL(3,2) NULL, [CourseID] INT NOT NULL, [StudentID] INT NOT NULL, PRIMARY KEY CLUSTERED ([EnrollmentID] ASC), CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID] FOREIGN KEY ([CourseID]) REFERENCES [dbo].[Course]([CourseID]) ON DELETE CASCADE, CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID] FOREIGN KEY ([StudentID]) REFERENCES [dbo].[Student]([StudentID]) ON DELETE CASCADE ) Generate Models Using Database Entities After creating the database and setting up the tables, you can go ahead and create a new MVC Empty Application. Right-click on the Models folder in your project and select Add → New Item. Then, select ADO.NET Entity Data Model. In the next wizard, choose Generate From Database and click Next. Set the Connection to your SQL database. Select your database and click Test Connection. A screen similar to the following will follow. Click Next. Select Tables, Views, and Stored Procedures and Functions. Click Finish. You will see the Model View created as shown in the following screenshot. The above operations would automatically create a Model file for all the database entities. For example, the Student table that we created will result in a Model file Student.cs with the following code − namespace MvcModelExample.Models { using System; using System.Collections.Generic; public partial class Student { public Student() { this.Enrollments = new HashSet(); } public int StudentID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public Nullable EnrollmentDate { get; set; } public virtual ICollection Enrollments { get; set; } } } Print Page Previous Next Advertisements ”;