MVC Framework and Application Structure

9143 ワード

MVC Framework and Application Structure


Introduction


In an ASP.NET Web site, URLs typically map to files that are stored on disk (usually .aspx files). These .aspx files include markup and code that is processed in order to respond to the request.
The ASP.NET MVC framework maps URLs to server code differently than a typical ASP.NET Web site. Instead of mapping URLs to ASP.NET pages or handlers, the framework maps URLs to controller classes. Controller classes handle incoming requests, such as user input and interactions, and execute appropriate application and data logic, based on user input. (ASP.NET MVC controllers implement a pattern known as the Front Controller pattern.) A controller class typically calls a separate view component that generates 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 values to use as the action method's arguments, and handles any errors that might occur when the action method runs. It then renders the requested view. By default, each set of components is in a separate folder of an MVC Web application project.

URL Mapping


The ASP.NET MVC framework uses a URL-routing engine that provides flexibility for mapping URLs to controller classes. You can define routing rules that the ASP.NET MVC framework uses to evaluate incoming URLs and to select the appropriate controller. You can also have the routing engine automatically parse variables that are defined in the URL, and have the ASP.NET MVC framework pass the variable values to the controller as parameter arguments. For more information, see ASP.NET Routing and ASP.NET Routing in MVC Applications .

The MVC Framework and Postbacks


ASP.NET MVC framework does not use the 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 a Visual Studio project template that helps you create Web applications that are structured to support the MVC pattern. This template creates a new MVC Web application that is configured to have the required folders, item templates, and configuration-file entries.
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, instead of by selecting New Web Site.
When you create a new MVC Web application, Visual Studio gives you the option to create two projects at the same time. The first project is a Web project where you can implement your application. The second project is a testing project where you can write unit tests for your MVC components.
Note
Visual Studio 2008 Standard Edition does not offer the option to create a test project when you create an MVC application project.
You can use any unit-testing framework that is compatible with the .NET Framework in order to test ASP.NET MVC applications. Visual Studio 2008 Professional includes 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 project folders shown in the following figure:
The folders used in MVC applications are as follows:
  • App_Data. The App_Data folder is the physical store for data. This folder has the same role as it does in ASP.NET Web sites that use Web Forms pages.
  • Content folder. The Content folder is the recommended location to add content files such as scripts, cascading style sheet files, images, and so on. In general, the Content folder is for static files.
  • Controllers folder. The Controllers folder is the recommended location for controllers. The MVC framework requires the names of all controllers to end with "Controller"—for example, HomeController, LoginController, or ProductController.
  • Models folder. The Models folder is provided for classes that represent the application model for your MVC Web application. This usually includes code that defines objects and that defines the logic for interaction with the data store. Typically, the actual model objects will be in separate class libraries. However, when you create a new application, you might put classes here and then move them into separate class libraries at a later point in the development cycle.
  • Views folder. The Views folder is the recommended location for views. Views use .aspx, .ascx, and .master files, in addition to any other files that are related to rendering views. The Views folder contains a folder for each controller; the folder is named with the controller-name prefix. For example, if you have a controller named HomeController, the Views folder will contain a folder named Home. By default, when the ASP.NET MVC framework loads a view, it looks for an .aspx file that has the requested view name in the Views"controllerName folder. By default, there is also a folder named Shared in the Views folder, which does not correspond to any controller. The Shared folder is used for views that are shared across multiple controllers. For example, you can put the Web application's master page in the Shared folder.

  • In addition to the folders listed previously, an MVC Web application uses the Global.asax file to set global URL routing defaults, and it uses the Web.config file to configure the application.

    Setting Global URL Routing Defaults


    Routes are initialized in the Application_Start method of the Global.asax.cs or Global.asax.vb file. The following example shows a typical Global.asax file that includes default routing logic.
    Public Class GlobalApplication

    Inherits System.Web.HttpApplication



    Shared Sub RegisterRoutes(routes As RouteCollection)

    ' Note: Change the URL to "{controller}.mvc/{action}/{id}" to

    ' enable automatic support for IIS6 and for IIS7 classic mode.



    ' Handler to stop URL routing for Web resources.

    routes.Add( _

    New Route( _

    "{resource}.axd/{*pathInfo}", _

    New StopRoutingHandler()) _

    )



    ' MapRoute takes the following parameters, in order:

    ' (1) Route name

    ' (2) URL with parameters

    ' (3) Parameter defaults

    ' (4) Parameter constraints

    routes.MapRoute( _

    "Default", _

    "{controller}/{action}/{id}", _

    New With {.controller = "Home", .action = "Index", .id = ""} _

    )



    End Sub



    Sub Application_Start()

    RegisterRoutes(RouteTable.Routes)

    End Sub

    End Class
    public class GlobalApplication : System.Web.HttpApplication

    {

    public static void RegisterRoutes(RouteCollection routes)

    {

    // Note: Change the URL to "{controller}.mvc/{action}/{id}" to

    // enable automatic support for IIS6 and for IIS7 classic mode.



    // Handler to stop URL routing for Web resources.

    routes.Add(

    new Route(

    "{resource}.axd/{*pathInfo}",

    new StopRoutingHandler())

    );



    routes.MapRoute(

    "Default",

    "{controller}/{action}/{id}",

    new { controller = "Home", action = "Index", id = "" }

    );

    }



    protected void Application_Start()

    {

    RegisterRoutes(RouteTable.Routes);

    }

    }