ASP.NET MVC Framework

One of the things that many people have asked for over the years with ASP.NET is built-in support for developing web applications using a model-view-controller (MVC) based architecture.
Last weekend at the Alt.NET conference in Austin I gave the first public demonstration of a new ASP.NET MVC framework that my team has been working on. You can watch a video of my presentation about it on Scott Hanselman's blog here.
We'll be releasing a public preview of this ASP.NET MVC Framework a little later this year. We'll then ship it as a fully supported ASP.NET feature in the first half of next year.
What is a Model View Controller (MVC) Framework?
MVC is a framework methodology that divides an application's implementation into three component roles: models, views, and controllers.
* “Models” in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).
* “Views” in a MVC based application are the components responsible for displaying the application's user interface. Typically this UI is created off of the model data (for example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).
* “Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.
One of the benefits of using a MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.
The MVC pattern can also help enable red/green test driven development (TDD) – where you implement automated unit tests, which define and verify the requirements of new code, first before you actually write the code itself.
A few quick details about the ASP.NET MVC Framework
I'll be doing some in-depth tutorial posts about the new ASP.NET MVC framework in a few weeks once the bits are available for download (in the meantime the best way to learn more is to watch the video of my presentation).
A few quick details to share in the meantime about the ASP.NET MVC framework:
* It enables clean separation of concerns, testability, and TDD by default. All core contracts within the MVC framework are interface based and easily mockable (it includes interface based IHttpRequest/IHttpResponse intrinsics). You can unit test the application without having to run the Controllers within an ASP.NET process (making unit testing fast). You can use any unit testing framework you want to-do this testing (including NUnit, MBUnit, MS Test, etc).
* It is highly extensible and pluggable. Everything in the MVC framework is designed so that it can be easily replaced/customized (for example: you can optionally plug-in your own view engine, routing policy, parameter serialization, etc). It also supports using existing dependency injection and IOC container models (Windsor, Spring.Net, NHibernate, etc).
* It includes a very powerful URL mapping component that enables you to build applications with clean URLs. URLs do not need to have extensions within them, and are designed to easily support SEO and REST-friendly naming patterns. For example, I could easily map the /products/edit/4 URL to the “Edit” action of the ProductsController class in my project above, or map the /Blogs/scottgu/10-10-2007/SomeTopic/ URL to a “DisplayPost” action of a BlogEngineController class.
* The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and .Master markup files as “view templates” (meaning you can easily use existing ASP.NET features like nested master pages, <%= %> snippets, declarative server controls, templates, data-binding, localization, etc). It does not, however, use the existing post-back model for interactions back to the server. Instead, you'll route all end-user interactions to a Controller class instead – which helps ensure clean separation of concerns and testability (it also means no viewstate or page lifecycle with MVC based views).
* The ASP.NET MVC framework fully supports existing ASP.NET features like forms/windows authentication, URL authorization, membership/roles, output and data caching, session/profile state management, health monitoring, configuration system, the provider architecture, etc.
If you are looking to build your web applications using a MVC approach, I think you'll find this new ASP.NET MVC Framework option very clean and easy to use. It will enable you to easily maintain separation of concerns in your applications, as well as facilitate clean testing and TDD.
I'll post more tutorials in the weeks ahead on how the new MVC features work, as well as how you can take advantage of them.
Hope this helps,

Two weeks ago I blogged about a new MVC (Model View Controller) framework for ASP.NET that we are going to be supporting as an optional feature soon. It provides a structured model that enforces a clear separation of concerns within applications, and makes it easier to unit test your code and support a TDD workflow. It also helps provide more control over the URLs you publish in your applications, and can optionally provide more control over the HTML that is emitted from them.
Since then I've been answering a lot of questions from people eager to learn more about it. Given the level of interest I thought it might make sense to put together a few blog posts that describe how to use it in more detail. This first post is one of several I'll be doing in the weeks ahead.
A Simple E-Commerce Storefront Application
I'm going to use a simple e-commerce store application to help illustrate how the ASP.NET MVC Framework works. For today's post I'll be implementing a product listing/browsing scenario in it.
Specifically, we are going to build a store-front that enables end-users to browse a list of product categories when they visit the /Products/Categories URL on the site:

When a user clicks on a product category hyperlink on the above page, they'll navigate to a product category listing URL – /Products/List/CategoryName – that lists the active products within the specific category:

When a user clicks an individual product, they'll navigate to a product details URL – /Products/Detail/ProductID – that displays more details about the specific product they selected:

We'll build all of the above functionality using the new ASP.NET MVC Framework. This will enable us to maintain a “clean separation of concerns” amongst the different components of the application, and enable us to more easily integrate unit testing and test driven development.
Creating A New ASP.NET MVC Application
The ASP.NET MVC Framework includes Visual Studio Project Templates that make it easy to create a new web application with it. Simply select the File->New Project menu item and choose the “ASP.NET MVC Web Application” template to create a new web application using it.
By default when you create a new application using this option, Visual Studio will create a new solution for you and add two projects into it. The first project is a web project where you'll implement your application. The second is a testing project that you can use to write unit tests against it:

You can use any unit testing framework (including NUnit, MBUnit, MSTest, XUnit, and others) with the ASP.NET MVC Framework. VS 2008 Professional now includes built-in testing project support for MSTest (previously in VS 2005 this required a Visual Studio Team System SKU), and our default ASP.NET MVC project template automatically creates one of these projects when you use VS 2008.
We'll also be shipping project template downloads for NUnit, MBUnit and other unit test frameworks as well, so if you prefer to use those instead you'll also have an easy one click way to create your application and have a test project immediately ready to use with it.
Understanding the Folder Structure of a Project
The default directory structure of an ASP.NET MVC Application has 3 top-level directories:
* /Controllers
* /Models
* /Views
As you can probably guess, we recommend putting your Controller classes underneath the /Controllers directory, your data model classes underneath your /Models directory, and your view templates underneath your /Views directory.
While the ASP.NET MVC framework doesn't force you to always use this structure, the default project templates use this pattern and we recommend it as an easy way to structure your application. Unless you have a good reason to use an alternative file layout, I'd recommend using this default pattern.
Mapping URLs to Controller Classes
In most web frameworks (ASP, PHP, JSP, ASP.NET WebForms, etc), incoming URLs typically map to template files stored on disk. For example, a “/Products.aspx” or “/Products.php” URL typically has an underlying Products.aspx or Products.php template file on disk that handles processing it. When a http request for a web application comes into the web server, the web framework runs code specified by the template file on disk, and this code then owns handling the processing of the request. Often this code uses the HTML markup within the Products.aspx or Products.php file to help with generating the response sent back to the client.
MVC frameworks typically map URLs to server code in a different way. Instead of mapping URLs to template files on disk, they instead map URLs directly to classes. These classes are called “Controllers” and they own processing incoming requests, handling user input and interactions, and executing appropriate application and data logic based on them. A Controller class will then typically call a separate “View” component that owns generating the actual HTML output for the request.

The ASP.NET MVC Framework includes a very powerful URL mapping engine that provides a lot of flexibility in how you map URLs to Controller classes. You can use it to easily setup routing rules that ASP.NET will then use to evaluate incoming URLs and pick a Controller to execute. You can also then have the routing engine automatically parse out variables that you define within the URL and have ASP.NET automatically pass these to your Controller as parameter arguments. I'll be covering more advanced scenarios involving the URL routing engine in a future blog post in this series.
Default ASP.NET MVC URL Routing to Controller Classes
By default ASP.NET MVC projects have a preconfigured set of URL routing rules that enable you to easily get started on an application without needing to explicitly configure anything. Instead you can start coding using a default set of name-based URL mapping conventions that are declared within the ASP.NET Application class of the Global.asax file created by the new ASP.NET MVC project template in Visual Studio.
The default naming convention is to map the leading URL path of an incoming HTTP request (for example: /Products/) to a class whose name follows the pattern UrlPathController (for example: by default a URL leading with /Products/ would map to a class named ProductsController).
To build our e-commerce product browsing functionality, we'll add a new “ProductsController” class to our project (you can use the “Add New Item” menu in Visual Studio to easily create a Controller class from a template):

Our ProductsController class will derive from the System.Web.MVC.Controller base class. Deriving from this base class isn't required – but it contains some useful helper methods and functionality that we'll want to take advantage of later:

Once we define this ProductsController class within our project, the ASP.NET MVC framework will by default use it to process all incoming application URLs that start under the “/Products/” URL namespace. This means it will be automatically called to process the “/Products/Categories”, “/Products/List/Beverages”, and “/Products/Detail/3” URLs that we are going to want to enable within our store-front application.
In a future blog post we'll also add a ShoppingCartController (to enable end users to manage their shopping carts) and an AccountController (to enable end users to create new membership accounts on the site and login/logout of it). Once we add these two new controller classes to our project, URLs that start with /ShoppingCart/ and /Account/ will automatically be routed to them for processing.
Note: The ASP.NET MVC framework does not require that you always use this naming convention pattern. The only reason our application uses this by default is because there is a mapping rule that configures this that was automatically added to our ASP.NET Application Class when we created the new ASP.NET MVC Project using Visual Studio. If you don't like this rule, or want to customize it to use a different URL mapping pattern, just go into the ASP.NET Application Class (in Global.asax) and change it. I'll cover how to-do this in a future blog post (when I'll also show some of the cool scenarios the URL routing engine enables).
Understanding Controller Action Methods
Now that we have a created a ProductsController class in our project we can start adding logic to handle the processing of incoming “/Products/” URLs to the application.
When defining our e-commerce storefront use cases at the beginning of this blog post, I said we were going to implement three scenarios on the site: 1) Browsing all of the Product Categories, 2) Listing Products within a specific Category, and 3) Showing Details about a Specific Product. We are going to use the following SEO-friendly URLs to handle each of these scenarios:
URL Format Behavior URL Example
/Products/Categories Browse all Product Categories /Products/Categories
/Products/List/Category List Products within a Category /Products/List/Beverages
/Products/Detail/ProductID Show Details about a Specific Product /Products/Detail/34
There are a couple of ways we could write code within our ProductsController class to process these three types of incoming URLs. One way would be to override the “Execute” method on the Controller base class and write our own manual if/else/switching logic to look at the incoming URL being requested and then execute the appropriate logic to process it.
A much easier approach, though, is to use a built-in feature of the MVC framework that enables us to define “action methods” on our controller, and then have the Controller base class automatically invoke the appropriate action method to execute based on the URL routing rules in use for our application.
For example, we could add the below three controller action methods to our ProductsController class to handle our three e-commerce URL scenarios above:

The URL routing rules that are configured by default when a new project is created treat the URL sub-path that follows the controller name as the action name of the request. So if we receive a URL request of /Products/Categories, the routing rule will treat “Categories” as the name of the action, and the Categories() method will be invoked to process the request. If we receive a URL request of /Products/Detail/5, the routing rule will treat “Detail” as the name of the action, and the Detail() method will be invoked to process the request, etc.
Note: The ASP.NET MVC framework does not require that you always use this action naming convention pattern. If you want to use a different URL mapping pattern, just go into the ASP.NET Application Class (in Global.asax) and change it.
Mapping URL Parameters to Controller Action Methods
There are several ways to access URL parameter values within the action methods of Controller classes.
The Controller base class exposes a set of Request and Response objects that can be used. These objects have the exact same API structure as the HttpRequest/HttpResponse objects that you are already familiar with in ASP.NET. The one important difference is that these objects are now interface based instead of sealed classes (specifically: the MVC framework ships with new System.Web.IHttpRequest and System.Web.IHttpResponse interfaces). The benefit of having these be interfaces is that it is now easy to mock them – which enables easy unit testing of controller classes. I'll cover this in more depth in a future blog post.
Below is an example of how we could use the Request API to manually retrieve an ID querystring value from within our Detail action method in the ProductsController class:

The ASP.NET MVC framework also supports automatically mapping incoming URL parameter values as parameter arguments to action methods. By default, if you have a parameter argument on your action method, the MVC framework will look at the incoming request data to see if there is a corresponding HTTP request value with the same name. If there is, it will automatically pass it in as a parameter to your action method.
For example, we could re-write our Detail action method to take advantage of this support and make it cleaner like below:

In addition to mapping argument values from the querystring/form collection of a request, the ASP.NET MVC framework also allows you to use the MVC URL route mapping infrastructure to embed parameter values within the core URL itself (for example: instead of /Products/Detail?id=3 you could instead use /Products/Detail/3).
The default route mapping rule declared when you create a new MVC project is one with the format: “/[controller]/[action]/[id]”. What this means is that if there is any URL sub-path after the controller and action names in the URL, it will by default be treated as a parameter named “id” – and which can be automatically passed into our controller action method as a method argument.
This means that we can now use our Detail method to also handle taking the ID argument from the URL path (e.g: /Products/Detail/3):


赞(0) 打赏
分享到: 更多 (0)