ASP.NET MVC Overview
Introduction
The Model View Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web-forms pattern for creating MVC-based Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web-forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc namespace and is a fundamental, supported part of the System.Web namespace.
MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web forms and postbacks. Other types of Web applications will combine the two approaches; neither approach precludes the other.
The MVC framework includes the following components:
-
Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects also retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server.
Note
In small applications, the model is often a conceptual separation rather than a physical one. For example, if the application only reads a data set and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the data set takes on the role of a model object.
-
Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.
-
Controllers. Controllers are the components that handle user interaction, manipulate the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn queries the database by using the values.
The MVC pattern helps you to create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should exist in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.
In addition to managing complexity, the MVC pattern makes it easier to test applications than it is to test a traditional ASP.NET Web application. For example, in a traditional ASP.NET Web application, a single class is used both to display output and to respond to user input. Writing automated tests for traditional ASP.NET applications can be complex, because to test an individual page, you must instantiate the page class, all its child controls, and additional dependent classes in the application. Because so many classes are instantiated to run the page, it can be hard to write tests that focus exclusively on individual portions of the application. Tests for traditional ASP.NET applications can therefore be more difficult to implement than tests within an MVC application. Moreover, tests within a traditional ASP.NET application require a Web server. The MVC framework decouples the components and makes heavy use of interfaces, which makes it possible to test individual components in isolation from the rest of the framework.
The loose coupling between the three main components of an MVC application also promotes parallel development. For instance, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.
Advantages of an MVC-Based Web Application
The ASP.NET MVC framework offers the following advantages:
-
It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
-
It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
-
It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you design an application that supports a rich routing infrastructure. For more information, see Front Controller on the MSDN Web site.
-
It provides greater support for test driven development (TDD).
Advantages of a Web-Forms-Based Web Application
The traditional Web-forms based framework offers the following advantages:
-
It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web-forms-based application provides dozens of events that are supported in hundreds of server controls.
-
It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller on the MSDN Web site.
-
It uses view state or server-based forms, which can make managing state information easier.
Features of the ASP.NET MVC Framework
The ASP.NET MVC framework provides the following features:
-
Separation of application tasks (input logic, business logic, and UI logic), testability, and test-driven development (TDD) by default. All core contracts within the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application. You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework.
-
An extensible and pluggable framework. The components of the ASP.NET MVC framework are designed so that they can be easily replaced or customized. You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports using existing Dependency Injection (DI) and Inversion of Control (IOC) container models. DI allows you to inject objects into a class, rather than relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file. This facilitates testing.
-
A powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing.
-
Support for using the markup in existing ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, and so on.
-
Support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, configuration system, the provider architecture, and other areas of ASP.NET.
Background
In an ASP.NET Web site, URLs typically map to files stored on disk (typically .aspx files). These .aspx files include code or markup that is processed in order to respond to the request.
The ASP.NET MVC framework maps URLs to server code differently than ASP.NET Web site applications. Instead of mapping URLs to ASP.NET pages or handlers, the framework maps URLs directly to controller classes. Controller classes handle incoming requests, such as user input and interactions, and also execute appropriate application and data logic, based on user input. A controller class typically calls a separate view component that generates the HTML output as the response.
The ASP.NET MVC framework separates the model, view, and controller components. The model component typically maintains state by persisting data in a database. The view component is selected by the controller and renders the appropriate UI. By default, the ASP.NET MVC framework uses the existing ASP.NET page (.aspx), master page (.master), and user control (.ascx) types for rendering to the browser. The controller component locates the appropriate action method in the controller, gets the values to use as the action method's arguments, handles all errors that might occur during the execution of the action, and renders the requested view. Each set of components exists in a separate folder of an MVC Web application project.
URL Mapping
The ASP.NET MVC framework incorporates a URL-mapping engine that provides flexibility for mapping URLs to controller classes. You can use the mapping engine to define routing rules that the ASP.NET MVC framework uses to evaluate incoming URLs and to select a controller to execute. You can also have the routing engine automatically parse variables defined in the URL and have the ASP.NET MVC framework pass these to the controller as parameter arguments. For more information, see URL Routing and URL Routing with MVC.
The MVC Framework and Postbacks
ASP.NET MVC framework does not use the traditional ASP.NET postback model for interactions with the server. Instead, all end-user interactions are routed to a controller class. This maintains separation between UI logic and business logic and helps testability. As a result, ASP.NET view state and ASP.NET page life-cycle events are not integrated with MVC-based views.
Creating an ASP.NET MVC Application
The ASP.NET MVC framework includes Visual Studio project templates that let you create Web applications that are structured to support the MVC pattern.
The MVC project templates include:
These templates are used to create a new Web application that is configured with the folders, templates, and configuration-file entries that are required for an ASP.NET MVC application.
By default, when you create a new Web application by using the ASP.NET MVC Web Application and Test template, Visual Studio creates a solution and adds two projects to the solution. The first project is a Web project where you can implement your application. The second project is a testing project that you can write unit tests for your MVC components.
Note
The ASP.NET MVC Web Application templates are based on the ASP.NET Web Application template. You select a new ASP.NET MVC project by selecting New Project from the File menu, rather than by selecting New Web Site.
You can use any unit-testing framework that is compatible with the .NET Framework to test ASP.NET MVC applications. Visual Studio 2008 Professional includes built-in testing project support for MSTest. For more information about MSTest, see MSTest.exe Command-Line Options on the MSDN Web site.
Web Application MVC Project Structure
When you create an ASP.NET MVC Web application project, MVC components are separated based on the following project folders:
-
Views folder. The Views folder is the recommended location for views. The views use .aspx, .ascx, and .master files, as well as any other files that are related to rendering views. The Views folder contains a folder for each controller that is named with the controller prefix. For instance, if you have a controller named HomeController, your Views folder will contain a folder named Home. When the ASP.NET MVC framework loads a view, by default it looks for an .aspx file with the requested view name in the Views\controllerName folder. There is also a default folder named Common that does not correspond to any controller. This is a useful location to put master pages, scripts, CSS files, and other files that are used when a view is rendered.
-
Controller folder. The Controllers folder is the recommended location for controllers.
-
Model folder. The Models folder is the recommended location for classes that represent the application model for your MVC Web application. Typically, this includes code that defines the logic for interaction with the data store, as well as object definitions.
-
App_Data. The App_Data folder is the physical store for data. This folder has the same role as it does in Web-forms-based ASP.NET Web applications.
In addition to the folders listed previously, a MVC Web application uses the following application elements:
-
Global.asax and Global.asax.cs (or Global.asax.vb in Visual Basic). In Global.asax.cs, routes are initialized in the Application_Start method. The following example shows a typical Global.asax file that includes default routing logic.
' Visual Basic
Public Class Global_asax
Inherits System.Web.HttpApplication
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
REM Note: Change Url= to Url="{controller}.mvc/{action}/{id}" to enable
REM automatic support on IIS6
RouteTable.Routes.Add(New Route With { _
.Url = "{controller}/{action}/{id}", _
.Defaults = New With {.action = "Index", .id = CStr(Nothing)}, _
.RouteHandler = New MvcRouteHandler _
})
RouteTable.Routes.Add(New Route With { _
.Url = "default.aspx", _
.Defaults = New With {.controller = "Home", .action = "Index", _
.id = CStr(Nothing)}, _
.RouteHandler = New MvcRouteHandler })
End Sub
End Class
// C#
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// Note: Change Url= to Url="{controller}.mvc/{action}/{id}" to enable
// automatic support on IIS6
RouteTable.Routes.Add(new Route
{
Url = "{controller}/{action}/{id}",
Defaults = new { action = "Index", id = (string)null },
RouteHandler = new MvcRouteHandler()
});
RouteTable.Routes.Add(new Route
{
Url = "Default.aspx",
Defaults = new { controller = "Home", action = "Index", id = (string)null },
RouteHandler = new MvcRouteHandler()
});
}
}
-
Configuration. The MVC Web application Web.config file registers HTTP modules. The httpModules section registers the UrlRoutingModule class, which parses the URL and routes requests to the appropriate handler. This entry enables the application to host MVC and non-MVC handlers in the same project. The following example shows the httpModules section for an ASP.NET MVC application.
<httpModules>
<add name="UrlRoutingModule"
type="System.Web.Mvc.UrlRoutingModule,
System.Web.Extensions, Version=3.6.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" />
</httpModules>
When you select an ASP.NET MVC Web Application and Test project template in VS Professional and above, the solution includes a test project. You can create tests by using the MVC templates and create mock implementations of the intrinsic interfaces.
Understanding the MVC Project Execution Process
Requests to an ASP.NET MVC-based Web application first pass through the UrlRoutingModule object (which is an HTTP module). This object parses the request and performs route selection. The UrlRoutingModule object selects the first Route object that matches the current request.
From the selected Route object, the UrlRoutingModule object obtains the IHttpContext object that will handle the request. By default, this is the MvcHandler object. The MvcHandler object then selects the controller that will ultimately handle the request. For more information, see URL Routing with MVC.
Note
When an ASP.NET MVC Web application runs in IIS 7, no file name extension is required for MVC projects. However, in IIS6, the handler requires that you map the .mvc file name extension to the ASP.NET ISAPI DLL.
The module and handler are the entry points to the ASP.NET MVC framework and perform the following actions:
-
Select the appropriate controller in an MVC Web application.
-
Obtain a specific controller instance.
-
Call the controller's Execute method.
The following table lists the stages of execution for an MVC Web project:
|
Stage
|
Details
|
|
Initial request
|
In the Global.asax file, routes are added to the RouteTable object.
|
|
Routing
|
The UrlRoutingModule module creates the RouteData object from the matched Route object in the RouteTable instance. Route data is used to determine which controller to request, and which action to invoke.
|
|
Map to controller
|
The MvcRouteHandler handler attempts to create the type name for the controller, based on data in the RouteData instance.
|
|
Invoke controller builder
|
The handler calls the global static CreateController method of the ControllerBuilder class, obtaining an IController instance.
If an IController instance is not returned, the handler returns an HTTP 500 error that indicates a server error.
|
|
Create controller
|
The ControllerBuilder instance creates a new controller directly, or uses an IControllerFactory object to create the controller.
|
|
Execute controller
|
The MvcHandler instance is added to the ControllerContext object and calls the controller's Execute method.
|
This topic is ASP.NET 3.5 Extensions pre-release documentation and is unsupported by Microsoft. Blank topics are included as placeholders and existing content is subject to change in future releases. To provide feedback or ask questions about the release, please go to the ASP.NET 3.5 Extensions forums.