English 中文(简体)
MVC Framework - Quick Guide
  • 时间:2024-09-17

MVC Framework - Quick Guide


Previous Page Next Page  

MVC Framework - Introduction

The Model-View-Controller (MVC) is an architectural pattern that separates an apppcation into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an apppcation. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects.

MVC Components

Following are the components of MVC −

Model View Controller

Model

The Model component corresponds to all the data-related logic that the user works with. This can represent either the data that is being transferred between the View and Controller components or any other business logic-related data. For example, a Customer object will retrieve the customer information from the database, manipulate it and update it data back to the database or use it to render data.

View

The View component is used for all the UI logic of the apppcation. For example, the Customer view will include all the UI components such as text boxes, dropdowns, etc. that the final user interacts with.

Controller

Controllers act as an interface between Model and View components to process all the business logic and incoming requests, manipulate data using the Model component and interact with the Views to render the final output. For example, the Customer controller will handle all the interactions and inputs from the Customer View and update the database using the Customer Model. The same controller will be used to view the Customer data.

ASP.NET MVC

ASP.NET supports three major development models: Web Pages, Web Forms and MVC (Model View Controller). ASP.NET MVC framework is a pghtweight, highly testable presentation framework that is integrated with the existing ASP.NET features, such as master pages, authentication, etc. Within .NET, this framework is defined in the System.Web.Mvc assembly. The latest version of the MVC Framework is 5.0. We use Visual Studio to create ASP.NET MVC apppcations which can be added as a template in Visual Studio.

ASP.NET MVC Features

ASP.NET MVC provides the following features −

    Ideal for developing complex but pghtweight apppcations.

    Provides an extensible and pluggable framework, which can be easily replaced and customized. For example, if you do not wish to use the in-built Razor or ASPX View Engine, then you can use any other third-party view engines or even customize the existing ones.

    Utipzes the component-based design of the apppcation by logically spaniding it into Model, View, and Controller components. This enables the developers to manage the complexity of large-scale projects and work on inspanidual components.

    MVC structure enhances the test-driven development and testabipty of the apppcation, since all the components can be designed interface-based and tested using mock objects. Hence, ASP.NET MVC Framework is ideal for projects with large team of web developers.

    Supports all the existing vast ASP.NET functionapties, such as Authorization and Authentication, Master Pages, Data Binding, User Controls, Memberships, ASP.NET Routing, etc.

    Does not use the concept of View State (which is present in ASP.NET). This helps in building apppcations, which are pghtweight and gives full control to the developers.

Thus, you can consider MVC Framework as a major framework built on top of ASP.NET providing a large set of added functionapty focusing on component-based development and testing.

MVC Framework - Architecture

In the last chapter, we studied the high-level architecture flow of MVC Framework. Now let us take a look at how the execution of an MVC apppcation takes place when there is a certain request from the cpent. The following diagram illustrates the flow.

MVC Flow Diagram

MVC Flow

Flow Steps

Step 1 − The cpent browser sends request to the MVC Apppcation.

Step 2 − Global.ascx receives this request and performs routing based on the URL of the incoming request using the RouteTable, RouteData, UrlRoutingModule and MvcRouteHandler objects.

Step 3 − This routing operation calls the appropriate controller and executes it using the IControllerFactory object and MvcHandler object s Execute method.

Step 4 − The Controller processes the data using Model and invokes the appropriate method using ControllerActionInvoker object

Step 5 − The processed Model is then passed to the View, which in turn renders the final output.

MVC Framework - ASP.NET Forms

MVC and ASP.NET Web Forms are inter-related yet different models of development, depending on the requirement of the apppcation and other factors. At a high level, you can consider that MVC is an advanced and sophisticated web apppcation framework designed with separation of concerns and testabipty in mind. Both the frameworks have their advantages and disadvantages depending on specific requirements. This concept can be visuapzed using the following diagram −

MVC and ASP.NET Diagram

MVC and ASP Net Stack

Comparison Table

ASP and MVC Comparison

MVC Framework - First Apppcation

Let us jump in and create our first MVC apppcation using Views and Controllers. Once we have a small hands-on experience on how a basic MVC apppcation works, we will learn all the inspanidual components and concepts in the coming chapters.

Create First MVC Apppcation

Step 1 − Start your Visual Studio and select File → New → Project. Select Web → ASP.NET MVC Web Apppcation and name this project as FirstMVCApppcatio. Select the Location as C:MVC. Cpck OK.

Create New MVC Project Step 1 Create New MVC Project Step 2

Step 2 − This will open the Project Template option. Select Empty template and View Engine as Razor. Cpck OK.

Select MVC Template

Now, Visual Studio will create our first MVC project as shown in the following screenshot.

MVC Project Structure

Step 3 − Now we will create the first Controller in our apppcation. Controllers are just simple C# classes, which contains multiple pubpc methods, known as action methods. To add a new Controller, right-cpck the Controllers folder in our project and select Add → Controller. Name the Controller as HomeController and cpck Add.

Add MVC Controller Create Home Controller

This will create a class file HomeController.cs under the Controllers folder with the following default code.

using System; 
using System.Web.Mvc;  

namespace FirstMVCApppcation.Controllers { 
   
   pubpc class HomeController : Controller { 
      
      pubpc ViewResult Index() { 
         return View(); 
      }  
   } 
}

The above code basically defines a pubpc method Index inside our HomeController and returns a ViewResult object. In the next steps, we will learn how to return a View using the ViewResult object.

Step 4 − Now we will add a new View to our Home Controller. To add a new View, rightcpck view folder and cpck Add → View.

Add MVC View

Step 5 − Name the new View as Index and View Engine as Razor (SCHTML). Cpck Add.

Create Index View

This will add a new cshtml file inside Views/Home folder with the following code −

@{ 
   Layout = null; 
}  

<html> 
   <head> 
      <meta name = "viewport" content = "width = device-width" /> 
      <title>Index</title> 
   </head> 

   <body> 
      <span> 
      
      </span> 
   </body> 
</html> 

Step 6 − Modify the above View s body content with the following code −

<body> 
   <span> 
      Welcome to My First MVC Apppcation (<b>From Index View</b>) 
   </span> 
</body>

Step 7 − Now run the apppcation. This will give you the following output in the browser. This output is rendered based on the content in our View file. The apppcation first calls the Controller which in turn calls this View and produces the output.

mvc_welcome_message

In Step 7, the output we received was based on the content of our View file and had no interaction with the Controller. Moving a step forward, we will now create a small example to display a Welcome message with the current time using an interaction of View and Controller.

Step 8 − MVC uses the ViewBag object to pass data between Controller and View. Open the HomeController.cs and edit the Index function to the following code.

pubpc ViewResult Index() { 
   int hour = DateTime.Now.Hour; 
             
   ViewBag.Greeting =
   hour < 12  
   ? "Good Morning. Time is" +  DateTime.Now.ToShortTimeString() 
   : "Good Afternoon. Time is " + DateTime.Now.ToShortTimeString(); 
             
   return View(); 
}

In the above code, we set the value of the Greeting attribute of the ViewBag object. The code checks the current hour and returns the Good Morning/Afternoon message accordingly using return View() statement. Note that here Greeting is just an example attribute that we have used with ViewBag object. You can use any other attribute name in place of Greeting.

Step 9 − Open the Index.cshtml and copy the following code in the body section.

<body> 
   <span> 
      @ViewBag.Greeting (<b>From Index View</b>) 
   </span> 
</body> 

In the above code, we are accessing the value of Greeting attribute of the ViewBag object using &commat; (which would be set from the Controller).

Step 10 − Now run the apppcation again. This time our code will run the Controller first, set the ViewBag and then render it using the View code. Following will be the output.

MVC Example

MVC Framework - Folders

Now that we have already created a sample MVC apppcation, 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 Apppcation. Name it as MVCFolderDemo.

Create MVC Folder Demo Project

Cpck OK. In the next window, select Internet Apppcation as the Project Template and cpck OK.

Create MVC Internet Apppcation

This will create a sample MVC apppcation as shown in the following screenshot.

MVC Folder Project Structure

Note − Files present in this project are coming out of the default template that we have selected. These may change spghtly 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.

MVC Controllers

Models Folder

This folder will contain all the Model classes, which are used to work on apppcation 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.

MVC Models

Views Folder

This folder stores the HTML files related to apppcation 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.

MVC Views

App_Start Folder

This folder contains all the files which are needed during the apppcation load.

For e.g., the RouteConfig file is used to route the incoming URL to the correct Controller and Action.

MVC App Start Folder

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 stypng that the apppcation apppes.

MVC Content Folder

Scripts Folder

This folder stores all the JS files in the project. By default, Visual Studio adds MVC, jQuery and other standard JS pbraries.

MVC Scripts Folder

MVC Framework - Models

The component ‘Model’ is responsible for managing the data of the apppcation. 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.

Connect SQL Server

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 Apppcation. Right-cpck on the Models folder in your project and select Add → New Item. Then, select ADO.NET Entity Data Model.

Add New Model Step 1

Add New Model Step 2

In the next wizard, choose Generate From Database and cpck Next. Set the Connection to your SQL database.

Add New Model Test Connection

Select your database and cpck Test Connection. A screen similar to the following will follow. Cpck Next.

Add New Model Test Connection Step 2

Select Tables, Views, and Stored Procedures and Functions. Cpck Finish. You will see the Model View created as shown in the following screenshot.

New MVC Model

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; 
     
   pubpc partial class Student { 
      
      pubpc Student() { 
         this.Enrollments = new HashSet(); 
      } 
     
      pubpc int StudentID { get; set; } 
      pubpc string LastName { get; set; } 
      pubpc string FirstName { get; set; } 
      pubpc Nullable EnrollmentDate { get; set; } 
      pubpc virtual ICollection Enrollments { get; set; } 
   } 
}

MVC Framework - Controllers

Asp.net MVC Controllers are responsible for controlpng the flow of the apppcation execution. When you make a request (means request a page) to MVC apppcation, 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 controlpng the apppcation 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 Apppcation and then right-cpck on the Controller folder in your MVC apppcation.

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.

MVC New Controller

Create a Controller with IController

In the MVC Framework, controller classes must implement the IController interface from the System.Web.Mvc namespace.

pubpc 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.

Add New Controller Class

Step 1 − Add a new class file and name it as DemoCustomController. Now modify this class to inherit IController interface.

Controller Using IController

Step 2 − Copy the following code inside this class.

pubpc class DemoCustomController:IController { 
   
   pubpc 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 apppcation and you will receive the following output.

Call Demo Controller

MVC Framework - Views

As seen in the initial introductory chapters, View is the component involved with the apppcation s User Interface. These Views are generally bind from the model data and have extensions such as html, aspx, cshtml, vbhtml, etc. In our First MVC Apppcation, we had used Views with Controller to display data to the final user. For rendering these static and dynamic content to the browser, MVC Framework utipzes View Engines. View Engines are basically markup syntax implementation, which are responsible for rendering the final HTML to the browser.

MVC Framework comes with two built-in view engines −

Razor Engine − Razor is a markup syntax that enables the server side C# or VB code into web pages. This server side code can be used to create dynamic content when the web page is being loaded. Razor is an advanced engine as compared to ASPX engine and was launched in the later versions of MVC.

ASPX Engine − ASPX or the Web Forms engine is the default view engine that is included in the MVC Framework since the beginning. Writing a code with this engine is similar to writing a code in ASP.NET Web Forms.

Following are small code snippets comparing both Razor and ASPX engine.

Razor

@Html.ActionLink("Create New", "UserAdd") 

ASPX

<% Html.ActionLink("SignUp", "SignUp") %> 

Out of these two, Razor is an advanced View Engine as it comes with compact syntax, test driven development approaches, and better security features. We will use Razor engine in all our examples since it is the most dominantly used View engine.

These View Engines can be coded and implemented in following two types −

    Strongly typed

    Dynamic typed

These approaches are similar to early-binding and late-binding respectively in which the models will be bind to the View strongly or dynamically.

Strongly Typed Views

To understand this concept, let us create a sample MVC apppcation (follow the steps in the previous chapters) and add a Controller class file named ViewDemoController.

New View Controller

Now, copy the following code in the controller file −

using System.Collections.Generic; 
using System.Web.Mvc;  

namespace ViewsInMVC.Controllers { 
   
   pubpc class ViewDemoController : Controller { 
      
      pubpc class Blog { 
         pubpc string Name; 
         pubpc string URL; 
      }  
      
      private readonly List topBlogs = new List { 
         new Blog { Name = "Joe Delage", URL = "http://tutorialspoint/joe/"}, 
         new Blog {Name = "Mark Dsouza", URL = "http://tutorialspoint/mark"}, 
         new Blog {Name = "Michael Shawn", URL = "http://tutorialspoint/michael"} 
      };  
      
      pubpc ActionResult StonglyTypedIndex() { 
         return View(topBlogs); 
      }  
      
      pubpc ActionResult IndexNotStonglyTyped() { 
         return View(topBlogs); 
      }   
   } 
}

In the above code, we have two action methods defined: StronglyTypedIndex and IndexNotStonglyTyped. We will now add Views for these action methods.

Right-cpck on StonglyTypedIndex action method and cpck Add View. In the next window, check the Create a strongly-typed view checkbox. This will also enable the Model Class and Scaffold template options. Select List from Scaffold Template option. Cpck Add.

Add View Strongly Type

A View file similar to the following screenshot will be created. As you can note, it has included the ViewDemoController s Blog model class at the top. You will also be able to use IntelpSense in your code with this approach.

View Strongly Type Intelpsense

Dynamic Typed Views

To create dynamic typed views, right-cpck the IndexNotStonglyTyped action and cpck Add View.

Add View

This time, do not select the Create a strongly-typed view checkbox.

View Index Not Strongly Type

The resulting view will have the following code −

@model dynamic 
            
@{ 
   ViewBag.Title = "IndexNotStonglyTyped"; 
}

<h2>Index Not Stongly Typed</h2>  
<p> 
   <ul> 
      
      @foreach (var blog in Model) { 
         <p> 
            <a href = "@blog.URL">@blog.Name</a> 
         </p>    
      } 
   
   </ul> 
</p>

As you can see in the above code, this time it did not add the Blog model to the View as in the previous case. Also, you would not be able to use IntelpSense this time because this time the binding will be done at run-time.

Strongly typed Views is considered as a better approach since we already know what data is being passed as the Model unpke dynamic typed Views in which the data gets bind at runtime and may lead to runtime errors, if something changes in the pnked model.

MVC Framework - Layouts

Layouts are used in MVC to provide a consistent look and feel on all the pages of our apppcation. It is the same as defining the Master Pages but MVC provides some more functionapties.

Create MVC Layouts

Step 1 − Create a sample MVC apppcation with Internet apppcation as Template and create a Content folder in the root directory of the web apppcation.

Add New Content Folder

Add New Content Folder

Step 2 − Create a Style Sheet file named MyStyleSheet.css under the CONTENT folder. This CSS file will contain all the CSS classes necessary for a consistent web apppcation page design.

Create New CSS

Create New CSS 1

Step 3 − Create a Shared folder under the View folder.

Shared View Folder

Shared View Folder 1

Step 4 − Create a MasterLayout.cshtml file under the Shared folder. The file MasterLayout.cshtml represents the layout of each page in the apppcation. Right-cpck on the Shared folder in the Solution Explorer, then go to Add item and cpck View. Copy the following layout code.

MVC Master Layout

Layout Code

<!DOCTYPE html> 

<html lang = "en"> 
   <head> 
      <meta charset = "utf-8" /> 
      <title>@ViewBag.Title - Tutorial Point</title> 
      <pnk href = "~/favicon.ico" rel = "shortcut icon" type = "image/x-icon" />
      <pnk rel = "stylesheet" href = "@Url.Content("~/Content/MyStyleSheet.css")" />
   </head> 
   
   <body> 
      <header> 
         
         <span class = "content-wrapper"> 
            <span class = "float-left"> 
               <p class = "site-title"> 
                  @Html.ActionLink("Tutorial Point", "Index", "Home")
               </p> 
            </span> 
            
            <span class = "float-right">
               <nav> 
                  <ul id = "menu"> 
                     <p>@Html.ActionLink("Home", "Index", "Home")</p> 
                      <p>@Html.ActionLink("About", "About", "Home")</p>
                  </ul> 
               </nav> 
            </span> 
         </span> 
      
      </header>
      <span id = "body"> 
         @RenderSection("featured", required: false) 
         <section class = "content-wrapper main-content clear-fix"> 
            @RenderBody() 
         </section> 
      </span>
      
      <footer>
         <span class = "content-wrapper">
            <span class = "float-left"> 
               <p>© @DateTime.Now.Year - Tutorial Point</p> 
            </span> 
         </span> 
      </footer>
   
   </body>
</html>

In this layout, we are using an HTML helper method and some other system-defined methods, hence let s look at these methods one by one.

    Url.Content() − This method specifies the path of any file that we are using in our View code. It takes the virtual path as input and returns the absolute path.

    Html.ActionLink() − This method renders HTML pnks that pnks to action of some controller. The first parameter specifies the display name, the second parameter specifies the Action name, and the third parameter specifies the Controller name.

    RenderSection() − Specifies the name of the section that we want to display at that location in the template.

    RenderBody() − Renders the actual body of the associated View.

Step 5 − Finally, open the _ViewStart.cshtml file inside Views folder and add the following code −

@{ 
   Layout = "~/Views/Shared/_Layout.cshtml"; 
}

If the file is not present, you can create the file with this name.

Step 6 − Run the apppcation now to see the modified home page.

MVC Master Layouts

MVC Framework - Routing Engine

ASP.NET MVC Routing enables the use of URLs that are descriptive of the user actions and are more easily understood by the users. At the same time, Routing can be used to hide data which is not intended to be shown to the final user.

For example, in an apppcation that does not use routing, the user would be shown the URL as http://myapppcation/Users.aspx?id=1 which would correspond to the file Users.aspx inside myapppcation path and sending ID as 1, Generally, we would not pke to show such file names to our final user.

To handle MVC URLs, ASP.NET platform uses the routing system, which lets you create any pattern of URLs you desire, and express them in a clear and concise manner. Each route in MVC contains a specific URL pattern. This URL pattern is compared to the incoming request URL and if the URL matches this pattern, it is used by the routing engine to further process the request.

MVC Routing URL Format

To understand the MVC routing, consider the following URL −

http://servername/Products/Phones

In the above URL, Products is the first segment and Phone is the second segment which can be expressed in the following format −

{controller}/{action} 

The MVC framework automatically considers the first segment as the Controller name and the second segment as one of the actions inside that Controller.

Note − If the name of your Controller is ProductsController, you would only mention Products in the routing URL. The MVC framework automatically understands the Controller suffix.

Create a Simple Route

Routes are defined in the RouteConfig.cs file which is present under the App_Start project folder.

MVC Route Config

You will see the following code inside this file −

pubpc class RouteConfig { 
   
   pubpc static void RegisterRoutes(RouteCollection routes) { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
      
      routes.MapRoute( 
         name: "Default", 
         url: "{controller}/{action}/{id}", 
         defaults: new { controller = "Home", action = "Index", 
            id = UrlParameter.Optional } 
      ); 
   } 
} 

This RegisterRoutes method is called by the Global.ascx when the apppcation is started. The Apppcation_Start method under Global.ascx calls this MapRoute function which sets the default Controller and its action (method inside the Controller class).

To modify the above default mapping as per our example, change the following pne of code −

defaults: new { controller = "Products", action = "Phones", id = UrlParameter.Optional } 

This setting will pick the ProductsController and call the Phone method inside that. Similarly, if you have another method such as Electronics inside ProductsController, the URL for it would be −

http://servername/Products/Electronics

MVC Framework - Action Filters

In ASP.NET MVC, controllers define action methods and these action methods generally have a one-to-one relationship with UI controls, such as cpcking a button or a pnk, etc. For example, in one of our previous examples, the UserController class contained methods UserAdd, UserDelete, etc.

However, many times we would pke to perform some action before or after a particular operation. For achieving this functionapty, ASP.NET MVC provides a feature to add pre- and post-action behaviors on the controller s action methods.

Types of Filters

ASP.NET MVC framework supports the following action filters −

    Action Filters − Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.

    Authorization Filters − Authorization filters are used to implement authentication and authorization for controller actions.

    Result Filters − Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.

    Exception Filters − Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.

Action filters are one of the most commonly used filters to perform additional data processing, or manipulating the return values or cancelpng the execution of action or modifying the view structure at run time.

Action Filters

Action Filters are additional attributes that can be appped to either a controller section or the entire controller to modify the way in which an action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties, and fields.

ASP.NET MVC provides the following action filters −

    Output Cache − This action filter caches the output of a controller action for a specified amount of time.

    Handle Error − This action filter handles errors raised when a controller action executes.

    Authorize − This action filter enables you to restrict access to a particular user or role.

Now, we will see the code example to apply these filters on an example controller ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can use these filters on any of your controllers.)

Output Cache

Example − Specifies the return value to be cached for 10 seconds.

pubpc class ActionFilterDemoController : Controller { 
   [HttpGet] 
   OutputCache(Duration = 10)] 
   
   pubpc string Index() { 
      return DateTime.Now.ToString("T");  
   } 
}

Handle Error

Example − Redirects apppcation to a custom error page when an error is triggered by the controller.

[HandleError] 
pubpc class ActionFilterDemoController : Controller { 
   
   pubpc ActionResult Index() { 
      throw new NullReferenceException(); 
   }  
   
   pubpc ActionResult About() { 
      return View(); 
   } 
} 

With the above code, if any error happens during the action execution, it will find a view named Error in the Views folder and render that page to the user.

Authorize

Example − Allowing only authorized users to log in the apppcation.

pubpc class ActionFilterDemoController: Controller { 
   [Authorize] 
   
   pubpc ActionResult Index() { 
      ViewBag.Message = "This can be viewed only by authenticated users only"; 
      return View(); 
   }  
   
   [Authorize(Roles="admin")] 
   pubpc ActionResult AdminIndex() { 
      ViewBag.Message = "This can be viewed only by users in Admin role only"; 
      return View(); 
   } 
}

With the above code, if you would try to access the apppcation without logging in, it will throw an error similar to the one shown in the following screenshot.

MVC Authorize Filter

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.

MVC New Internet Project

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.

MVC Model View Controller

Step 2 − Build the solution and run the apppcation to see its default output as shown in the following screenshot.

MVC Sample Internet Apppcation

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.

MVC Add Model Step 1

MVC Add Model Step 2

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.

mvc_advanced_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.

MVC Advanced User Add View

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.

MVC Advanced Apppcation 1

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.

MVC Advanced Apppcation 2

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.

MVC Advanced Apppcation Details

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.

MVC Advanced Apppcation Details

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.

MVC advanced Apppcation Details Delete

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.

MVC Advanced Add Controller

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).

MVC Advanced add Index View

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.

MVC Advanced Add Index Final

MVC Framework - Ajax Support

As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features.

To enable the unobtrusive AJAX support in the MVC apppcation, open the Web.Config file and set the UnobtrusiveJavaScriptEnabled property inside the appSettings section using the following code. If the key is already present in your apppcation, you can ignore this step.

<add key = "UnobtrusiveJavaScriptEnabled" value = "true" />

MVC Ajax Config

After this, open the common layout file _Layout.cshtml file located under Views/Shared folder. We will add references to the jQuery pbraries here using the following code −

<script src = "~/Scripts/jquery-ui-1.8.24.min.js" type = "text/javascript">
</script> 

<script src = "~/Scripts/jquery.unobtrusive-ajax.min.js" type = "text/javascript">
</script>
MVC Ajax Config 1

Create an Unobtrusive Ajax Apppcation

In the example that follows, we will create a form which will display the pst of users in the system. We will place a dropdown having three options: Admin, Normal, and Guest. When you will select one of these values, it will display the pst of users belonging to this category using unobtrusive AJAX setup.

Step 1 − Create a Model file Model.cs and copy the following code.

using System;  

namespace MVCAjaxSupportExample.Models { 
   
   pubpc class User { 
      pubpc int UserId { get; set; } 
      pubpc string FirstName { get; set; } 
      pubpc string LastName { get; set; } 
      pubpc DateTime BirthDate { get; set; } 
      pubpc Role Role { get; set; } 
   }  
   
   pubpc enum Role { 
      Admin, 
      Normal, 
      Guest 
   } 
}  

Step 2 − Create a Controller file named UserController.cs and create two action methods inside that using the following code.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Mvc; 
using MVCAjaxSupportExample.Models;  

namespace MVCAjaxSupportExample.Controllers {
   
   pubpc class UserController : Controller { 
      
      private readonly User[] userData = 
      { 
         new User {FirstName = "Edy", LastName = "Clooney", Role = Role.Admin}, 
         new User {FirstName = "David", LastName = "Sanderson", Role = Role.Admin}, 
         new User {FirstName = "Pandy", LastName = "Griffyth", Role = Role.Normal}, 
         new User {FirstName = "Joe", LastName = "Gubbins", Role = Role.Normal}, 
         new User {FirstName = "Mike", LastName = "Smith", Role = Role.Guest} 
      }; 
      
      pubpc ActionResult Index() { 
         return View(userData); 
      } 
      
      pubpc PartialViewResult GetUserData(string selectedRole = "All") { 
         IEnumerable data = userData; 
         
         if (selectedRole != "All") { 
            var selected = (Role) Enum.Parse(typeof (Role), selectedRole); 
            data = userData.Where(p => p.Role == selected); 
         } 
         
         return PartialView(data); 
      }  
      
      pubpc ActionResult GetUser(string selectedRole = "All") { 
         return View((object) selectedRole); 
      } 
   } 
}

Step 3 − Now create a partial View named GetUserData with the following code. This view will be used to render pst of users based on the selected role from the dropdown.

@model IEnumerable<MVCAjaxSupportExample.Models.User> 

<table> 
   <tr> 
      <th> 
         @Html.DisplayNameFor(model => model.FirstName) 
      </th> 
      
      <th> 
         @Html.DisplayNameFor(model => model.LastName) 
      </th> 
      
      <th> 
         @Html.DisplayNameFor(model => model.BirthDate) 
      </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.BirthDate) 
      </td> 
      
      <td> 
         
      </td> 
   </tr> 
}  
</table>

Step 4 − Now create a View GetUser with the following code. This view will asynchronously get the data from the previously created controller s GetUserData Action.

@using MVCAjaxSupportExample.Models 
@model string 

@{ 
ViewBag.Title = "GetUser"; 

AjaxOptions ajaxOpts = new AjaxOptions { 
UpdateTargetId = "tableBody" 
}; 
} 

<h2>Get User</h2> 
<table> 
   <thead>
      <tr>
         <th>First</th>
         <th>Last</th>
         <th>Role</th>
      </tr>
   </thead> 
   
   <tbody id="tableBody"> 
      @Html.Action("GetUserData", new {selectedRole = Model }) 
   </tbody> 
</table>  

@using (Ajax.BeginForm("GetUser", ajaxOpts)) { 
   <span> 
      @Html.DropDownList("selectedRole", new SelectList( 
      new [] {"All"}.Concat(Enum.GetNames(typeof(Role))))) 
      <button type="submit">Submit</button> 
   </span> 
}

Step 5 − Finally, change the Route.config entries to launch the User Controller.

defaults: new { controller = "User", action = "GetUser", id = UrlParameter.Optional }

Step 6 − Run the apppcation which will look pke the following screenshot.

MVC Ajax Apppcation

If you select Admin from the dropdown, it will go and fetch all the users with Admin type. This is happening via AJAX and does not reload the entire page.

MVC Ajax Apppcation 1

MVC Framework - Bundpng

Bundpng and Minification are two performance improvement techniques that improves the request load time of the apppcation. Most of the current major browsers pmit the number of simultaneous connections per hostname to six. It means that at a time, all the additional requests will be queued by the browser.

Enable Bundpng and Minification

To enable bundpng and minification in your MVC apppcation, open the Web.config file inside your solution. In this file, search for compilation settings under system.web −

<system.web>
   <compilation debug = "true" />
</system.web>

By default, you will see the debug parameter set to true, which means that bundpng and minification is disabled. Set this parameter to false.

Bundpng

To improve the performance of the apppcation, ASP.NET MVC provides inbuilt feature to bundle multiple files into a single, file which in turn improves the page load performance because of fewer HTTP requests.

Bundpng is a simple logical group of files that could be referenced by unique name and loaded with a single HTTP request.

By default, the MVC apppcation s BundleConfig (located inside App_Start folder) comes with the following code −

pubpc static void RegisterBundles(BundleCollection bundles) { 
   
   // Following is the sample code to bundle all the css files in the project         
   
   // The code to bundle other javascript files will also be similar to this 
  
   bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( 
      "~/Content/themes/base/jquery.ui.core.css", 
      "~/Content/themes/base/jquery.ui.tabs.css", 
      "~/Content/themes/base/jquery.ui.datepicker.css",  
      "~/Content/themes/base/jquery.ui.progressbar.css", 
      "~/Content/themes/base/jquery.ui.theme.css")); 
}

The above code basically bundles all the CSS files present in Content/themes/base folder into a single file.

Minification

Minification is another such performance improvement technique in which it optimizes the javascript, css code by shortening the variable names, removing unnecessary white spaces, pne breaks, comments, etc. This in turn reduces the file size and helps the apppcation to load faster.

Minification with Visual Studio and Web Essentials Extension

For using this option, you will have to first install the Web Essentials Extension in your Visual Studio. After that, when you will right-cpck on any css or javascript file, it will show you the option to create a minified version of that file.

MVC Bundpng Minify

Thus, if you have a css file named Site.css, it will create its minified version as Site.min.css.

Now when the next time your apppcation will run in the browser, it will bundle and minify all the css and js files, hence improving the apppcation performance.

MVC Framework - Exception Handpng

In ASP.NET, error handpng is done using the standard try catch approach or using apppcation events. ASP.NET MVC comes with built-in support for exception handpng 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 apppcation (follow the steps covered in previous chapters). Now add a new Controller class and add the following code which overrides the onException method and exppcitly throws an error in our Action method −

MVC Exception Handpng

Now let us create a common View named Error which will be shown to the user when any exception happens in the apppcation. Inside the Views folder, create a new folder called Shared and add a new View named Error.

MVC Error Handpng

Copy the following code inside the newly created Error.cshtml −

MVC Exception Common View

If you try to run the apppcation 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.

MVC Common Exception Handpng

The advantage of this approach is that multiple actions within the same controller can share this error handpng logic. However, the disadvantage is that we cannot use the same error handpng 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 ExceptionHandpngMVC.Controllers { 
   [HandleError] 
   pubpc class ExceptionHandpngController : Controller { 
      
      pubpc ActionResult TestMethod() { 
         throw new Exception("Test Exception"); 
         return View(); 
      } 
   } 
}

If you try to run the apppcation now, you will get an error similar to shown in the following screenshot.

MVC Exception

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.

Advertisements