KiMoGiGi 技术文集

不在乎选择什么,而在乎坚持多久……

IT博客 首页 联系 聚合 管理
  185 Posts :: 14 Stories :: 48 Comments :: 0 Trackbacks
链接:http://quickstarts.asp.net/3-5-extensions/mvc/MVCOverview.aspx
我的翻译:ASP.NET MVC 概述

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 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 does not use view state or server-based forms. This makes it ideal for developers who want full control over the behavior of an application.

On the other hand, Web forms-based applications support 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. MVC uses a Front Controller pattern that enables you design an application that completely separates the tasks of presentation, business logic, and data access, and that supports a rich routing infrastructure. Web forms applications use a page-controller pattern that adds functionality to individual pages. These two patterns can be mixed as needed.

The MVC components are as follows:

  • Models - Model objects are the parts of your application that implement the domain logic. 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 smaller 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 testing applications easier than testing 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 test 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.

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. 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 and Inversion of Control (IOC) container models.

  • 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. For example, you could map the /products/edit/4 URL to the Edit action of a ProductsController class in your project, or map the /Blogs/YourSite/10-10-2007/SomeTopic/ URL to a DisplayPost action of a BlogEngineController class. URLs do not have to reference file names.

  • Support for using the markup in existing ASP.NET pages (.aspx files), user controls (.ascx files), and master pages (.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 in a different way. 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 maintains state by typically persisting data inside 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 subdirectory of an MVC Web application project.

URL Mapping

The ASP.NET MVC framework includes 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.

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 Web Application template is used to create a new Web application that is configured with the subdirectories, 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 this 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.

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.

Understanding 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 directory contains a folder for each controller that is named with the controller prefix. When loading a view, by default the ASP.NET MVC framework will look for an .aspx file with the requested view name in the Views\controllerName folder. There is also a default directory 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 rendering a view.

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

  • App_Data. 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.

    public class Global : System.Web.HttpApplication {
        protected void Application_Start(object sender, EventArgs e) {
        RouteTable.Routes.Add(new Route {
        Url = "[controller]/[action]/[id]",
        Defaults = new { action = "Index", id = (string)null },
        RouteHandler = typeof(MvcRouteHandler)
        });
        }
        }
  • Configuration. The MVC Web application Web.config file registers HTTP handlers and HTTP modules. The httpHandlers section registers the MvcHandler class, which routes requests to the appropriate controller. The following example shows the httpHandlers section for an ASP.NET MVC application.

    <httpHandlers>
        <add verb="*" path="*.mvc" type="System.Web.Mvc.MvcHandler,
        System.Web.Extensions, Version=3.6.0.0, Culture=neutral,
        PublicKeyToken=31BF3856AD364E35"/>
        </httpHandlers>

    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 create an MVC Web application project, 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 a Web site that is built by using the MVC framework are routed through an ASP.NET HTTP module and to an HTTP handler.

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 context and calls the controller's Execute method.

Example

The following code shows the default structure that is created by Visual Studio when you create a new MVC Web application.

Language:
View

This topic is ASP.NET 3.5 Extensions Preview 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 Preview forums.

posted on 2007-12-10 21:26 KiMoGiGi 阅读(2510) 评论(0)  编辑 收藏 引用 所属分类: ASP.NETC# / Winforms
只有注册用户登录后才能发表评论。