ASP.NET MVC Source Refresh Preview
We recently opened up a new ASP.NET CodePlex Project that we will be using to provide previews (with buildable source code) for several upcoming ASP.NET features and releases.
Last month we used it to publish the first drop of the ASP.NET MVC source code. This first drop included the source for the ASP.NET MVC Preview 2 release that we shipped at MIX, along with Visual Studio project files to enable you to patch and build it yourself.
A few hours ago we published a refresh of the ASP.NET MVC source code on the site. This source refresh is not an official new ASP.NET MVC preview release - instead it is an interim drop that provides a look at the current state of the source tree. We will ship the official "ASP.NET MVC Preview 3" release in a few weeks after we finish up some more work (more features and tweaks to existing ones, better VS tool integration, VS express edition support, documentation, etc). If you are someone who wants a hassle-free installation of ASP.NET MVC to use that ships with documentation and full tool support you'll probably want to wait for this official preview release. If you are someone who wants a chance to see an early "preview of the preview" and have the opportunity to start using and giving feedback on some of the features immediately, today's source refresh is probably interesting to look at.
Improvements with this ASP.NET MVC Source Refresh
This week's update (which you can download here) includes a number of improvements to ASP.NET MVC. Some of these include:
-
In addition to posting the source code for the ASP.NET MVC framework, we are also posting the source code for the unit tests that we use to test it. These tests are implemented using MSTest and the open source Moq mocking framework. A VS 2008 project file for the unit tests is included to make it easy to build and run them locally within your VS 2008 IDE.
-
Significantly easier support for testing Controller classes. You can now unit test common Controller scenarios without having to mock any objects (more details on how this works below).
-
Several nice feature additions and usability improvements to the URL routing system (more details below).
Creating a New ASP.NET MVC Project
You can build your own copy of the ASP.NET MVC assemblies by downloading the MVC source and compiling it locally, or alternatively you can download a VS Template package to get a pre-built version of them along with a Visual Studio project template that you can use to quickly build a new ASP.NET MVC Project that uses the latest bits.
After you install the ASP.NET MVC source refresh .VSI template, a new "ASP.NET MVC Application" project template will show up under the "My Templates" section of your "New Project" dialog:
This new "My Templates" version of the MVC project template lives side-by-side with the previous ASP.NET MVC Preview 2 release (which you can see above it in the main project templates section of the dialog). This allows you to safely create new projects and and use both the latest source version and the last official preview version on the same machine.
When you create a new project using this updated ASP.NET MVC Project template you'll by default get a project that looks like below:
This new project solution contains one Controller ("HomeController") under the "\Controllers" directory and two View templates ("About" and "Index") under the "\Views\Home" sub-directory. Both view templates are based on a common master page for the site ("Site.master"), all of whose styles are defined within a "Site.css" file under the "\Content" directory.
When you run the application the built-in web-server will automatically start up and you'll see the site's "Home" content:
Clicking the "About us" tab will then display the "About" content:
The "HomeController" class in the project is responsible for handling both of the URLs above and has two action methods like below:
The default "Site.master" template looks for a "Title" value in the ViewData collection and uses it to render the <title> element of the HTML page. The default "Index" view template looks for a "Message" value and uses it to render the home page's welcome message. You can obviously go in and customize these files however you want.
Controller Changes with this ASP.NET MVC Drop
If you were reading the above code closely you might have noticed a few changes with how Controller classes are by default implemented using this new ASP.NET MVC source refresh drop.
With the ASP.NET MVC Preview 2 release the above HomeController action methods would have instead been implemented like below:
The MVC feature team is experimenting with a few ideas in this week's drop and are trying out some new ideas:
-
Action methods on Controllers now by default return an "ActionResult" object (instead of void). This ActionResult object indicates the result from an action (a view to render, a URL to redirect to, another action/route to execute, etc).
-
The RenderView(), RedirectToAction(), and Redirect() helper methods on the Controller base class now return typed ActionResult objects (which you can further manipulate or return back from action methods).
-
The RenderView() helper method can now be called without having to explicitly pass in the name of the view template to render. When you omit the template name the RenderView() method will by default use the name of the action method as the name of the view template to render. So calling "RenderView()" with no parameters inside the "About()" action method is now the same as explicitly writing "RenderView('About')".
It is pretty easy to update existing Controller classes built with Preview 2 to use this new pattern (just change void to ActionResult and add a return statement in front of any RenderView or RedirectToAction helper method calls).
Returning ActionResult Objects from Action Methods
So why change Controller action methods to return ActionResult objects by default instead of returning void? A number of other popular Web-MVC frameworks use the return object approach (including Django, Tapestry and others), and we found for ASP.NET MVC that it brought a few nice benefits:
-
It enables much cleaner and easier unit testing support for Controllers. You no longer have to mock out methods on the Response object or ViewEngine objects in order to unit test the response behavior of action methods. Instead, you can simply assert conditions using the ActionResult object returned from calling the Action method within your unit test (see next section below).
-
It can make Controller logic flow intentions a little clearer and more explicit in scenarios where there might be two different outcomes depending on some condition (for example: redirect if condition A is true, otherwise render a view template it is false). This can make non-trivial controller action method code easier to read and follow.
-
It enables some nice composition scenarios where a FilterActionAttribute can take the result of an action method and modify/transform it before executing it. For example: a "Browse" action on a ProductCatalog controller might return an RenderActionResult that indicates it wants to render a "List" view of products. A FilterActionAttribute declaratively set on the controller class could then have a chance to customize the specific "List" view template rendered to be either List-html.aspx or List-xml.aspx depending on the preferred MIME type of the client. Multiple FilterActionAttributes can also optionally be chained together to flow the results from one to another.
-
It provides a nice extensibility mechanism for people (including ourselves) to add additional features in the future. New ActionResult types can be easily created by sub-classing the ActionResult base class and overriding the "ExecuteResult" method. It would be easy to create a "RenderFile()" helper method, for example, that a developer writing an action could call to return a new "FileActionResult" object.
-
It will enable some nice Asynchronous execution scenarios in the future. Action methods will be able to return an AsyncActionResult object which indicates that they are waiting on a network operation and want to yield back the worker thread so that ASP.NET can use it to execute another request until the network call completes. This will enable developers to avoid blocking threads on a server, and support very efficient and scalable code.
One of the goals with this interim preview is to give people a chance to play around with this new approach and do real-world app-building and learning with it.
We will also post an alternative Controller base class sample that you can use if you still prefer the previous "void" action return approach. We deliberately didn't include this alternative Controller base class in this source refresh drop, though, because we want to encourage folks to give the "ActionResult" return approach a try and send us their app-building feedback on it.
How To Unit Test Controller Action Methods
I mentioned above that the new ActionResult approach can make unit testing controllers much easier (and avoid the need to use mocking for common scenarios). Let's walk through an example of this in action.
Consider the simple NumberController class below:
This Controller class has an "IsEvenNumber" action method that takes a number as a URL argument. The IsEvenNumber action method first checks whether the number is negative - in which case it redirects the user to an error page. If it is a positive number it determines whether the number is even or odd, and renders a view template that displays an appropriate message:
Writing unit tests for our "IsEvenNumber" action method is pretty easy thanks to the new ActionResult approach.
Below is an example unit test that verifies that the correct Http redirect occurs when a negative number is supplied (for example: /Number/IsEvenNumber/-1):
Notice above how we did not need to mock any objects to test our action method. Instead we simply instantiated the NumberController class and called the action method directly (passing in a negative number) and assigned the return value to a local "result" variable. I used the C# "as type" syntax above to cast the "result" variable as a strongly typed "HttpRedirectResult" type.
What is nice about the C# "as" keyword is that it will assign the value as null instead of throwing an exception if the cast fails (for example: if the action method returned a RenderViewResult instead). This means I can easily add an assertion check in my test to verify that the result is not null in order to verify that an Http redirect happened. I can then add a second assertion check to verify that the correct redirect URL was specified.
Testing the scenarios where non-zero numbers are passed in is also easy. To do this we'll create two test methods - one testing even numbers and one testing odd numbers. In both tests we'll assert that a RenderViewResult was returned, and then verify that the correct "Message" string was passed within the ViewData associated with the view:
We can then right click on our NumberControllerTest class inside VS 2008 and choose the "Run Tests" menu item:
This will execute our three unit tests in-memory (no web-server required) and report back on whether our NumberController.IsEvenNumber() action method is performing the right behavior:
Note: with this week's source drop you still need to use mocking to test the TempData property on Controllers. Our plan is to not require mocking to test this with the ASP.NET MVC Preview 3 drop in a few weeks.
MapRoute Helper Method
URL routing rules within ASP.NET MVC applications are typically declared within the "RegisterRoutes" method of the Global.asax class.
With ASP.NET MVC Previews 1 and 2 routes were added to the routes collection by instantiating a Route object directly, wiring it up to a MvcRouteHandler class, and then by setting the appropriate properties on it to declare the route rules:
The above code will continue to work going forward. However, you can also now take advantage of the new "MapRoute" helper method which provides a much simpler syntax to-do the same thing. Below is the convention-based URL route configured by default when you create a new ASP.NET MVC project (which replaces the code above):
The MapRoute() helper method is overloaded and takes two, three or four parameters (route name, URL syntax, URL parameter default, and URL parameter regular expression constraints).
You can call MapRoute() as many times as you want to register multiple named routes in the system. For example, in addition to the default convention rule, we could add a "Products-Browse" named routing rule like below:
We can then refer to this "Products-Browse" rule explicitly within our Controllers and Views when we want to generate a URL to it. For example, we could use the Html.RouteLink view helper to indicate that we want to link to our "Products-Browse" route and pass it a "Food" category parameter using code in our view template like below:
This view helper would then access the routing system and output an appropriate HTML hyperlink URL like below (note: how it did automatic parameter substitution of the category parameter into the URL using the route rule):
Note: with this week's source drop you need to pass-in the controller and action parameters (in addition to the Category param) to the Html.RouteLink() helper to resolve the correct route URL to generate. The ASP.NET MVC Preview 3 drop in a few weeks will not require this, and allow you to use the Html.RouteLink call exactly as I've written it above to resolve the route.
Other URL Route Mapping Features
This week's MVC source drop also supports a bunch of new URL route mapping features. You can now include "-", ".", ";" or any other characters you want as part of your route rules.
For example, using a "-" separator you can now parse the language and locale values from your URLs separately using a rule like below:
This would pass appropriate "language", "locale", and "category" parameters to the ProductsController.Browse action method when invoked:
URL Route Rule | Example URL | Parameters Passed to Action method |
{language}-{locale}/products/browse/{category} | /en-us/products/browse/food | language=en, locale=us, category=food |
/en-uk/products/browse/food | language=en, locale=uk, category=food |
Or you can use the "." file extension type at the end of a URL to determine whether to render back the result in either a XML or HTML format:
This would pass both "category" and a "format" parameters to the ProductsController.Browse action method when invoked:
URL Route Rule | Example URL | Parameters Passed to Action method |
products/browse/{category}.{format} | /products/browse/food.xml | category=food, format=xml |
/products/browse/food.html | category=food, format=html |
ASP.NET MVC Preview 2 introduced wildcard route rules. For example, you can indicate in a rule to pass all remaining URI content on as a named parameter to an action method:
This would pass a "contentUrl" parameter to the WikiController.DisplayPage action method when invoked:
URL Route Rule | Example URL | Parameters Passed to Action method |
Wiki/Pages/{*contentUrl} | /Wiki/Pages/People/Scott | contentUrl="People/Scott" |
/Wiki/Pages/Countries/UK | contentUrl="Countries/UK" |
These wildcard routes continue to work fine with this week's preview - and are very useful to look at if you are building a blogging, wiki, cms or other content based system.
Note that in addition to using the new routing system for ASP.NET MVC scenarios, we are also now using the same routing system within ASP.NET Dynamic Data (which uses ASP.NET Web Forms).
Summary
Hopefully the above post provides a quick update on some of the new features and changes exposed with this week's ASP.NET MVC source update drop.
You can download it here if you want to start using it immediately. Alternatively, you can wait a few weeks for the official ASP.NET MVC Preview 3 drop - which will have some more features (and incorporate feedback people provide on this week's drop), deliver a more seamless installer, provide nice VS integration, and deliver up to date documentation.
For any questions/issues with this week's drop of ASP.NET MVC, make sure to also check out the ASP.NET MVC forum on www.asp.net.
Hope this helps,
Scott