Overall, ASP.NET is one of the most popular web application frameworks along with PHP, Java and others. However, the classic ASP.NET WebForms style of application development also has its limitations. For instance, cleanly separating the user interface from the application logic and database access can be a challenge in WebForms applications. Thus, Microsoft created ASP.NET MVC. MVC stands for Model View Controller.
The ASP.NET MVC technology has already been introduced earlier (see the Resources section at the end of this article), and thus this article focuses on the new and improved features planned for .NET Framework version 4.0 that should become available in Spring, 2010. Originally Microsoft announced Visual Studio 2010 would launch on March 22nd, 2010, but most recent announcements indicate delays. As far as version numbers are concerned, the next version of ASP.NET MVC will be assigned the version number 2.0. In this article, you will learn what's new and improved in the newest Release Candidate (RC) version of ASP.NET MVC 2. At the time of this writing (late December, 2009) the latest beta version of Visual Studio 2010 is Beta 2, and it doesn't yet come with the ASP.NET MVC 2 RC. The unfortunate thing is that if you are using Visual Studio 2010 Beta 2, you cannot yet test MVC 2 RC with that version (you can naturally continue to use the older Beta 2 version). Instead, you must test the MVC 2 RC on Visual Studio 2008 SP1.
Exploring the new features
ASP.NET MVC 2 is an evolutional update to the framework. The basic features of the original version 1.0 are intact, but new features make development easier and result in cleaner code. The following list summarizes the key new features:
- Area support and multi-project routing
- Improved syntax for handling posts (form submits) in controllers
- HtmlHelper object improvements
- Attribute support for field validation in models
- Globalization of validation messages
- Field templates with custom user controls, and more.
Let's walk through each of these in more detail, starting from the top. In MVC 1.0, each view page was thought of as being a separate unit, and served to the browser as a single unit, possibly combined with a master page. However, if you wanted to combine, say, two views into a single page, you either had to manually render one of the pages or create a user control (.ascx) from one of the views, and then use that control inside the main view page. Although user controls are a fine solution, they break out of the MVC pattern.
In MVC 2, you can utilize so-called areas to solve the problem (Figure 1). With area support, you can combine different view pages into a single, larger view similar to the way you can build master pages (.master) and designate parts of them to be filled with content at run-time. It is possible to combine areas into views both inside a single MVC web project ("intra-project areas"), or combine areas in different projects into views ("inter-project areas"), accessible through direct URLs in the same scope.
Figure 1. Areas can be used to created complex views.
The following paragraphs walk you through using areas inside a single project. If you wanted to combine multiple MVC web projects into a single larger application, you would need to manually edit the .csproj project files of each project part of the overall solution (the edits you need to do are documented in the .csproj XML comments), add proper project references from the child projects to the master project, and then register routes using the MapAreaRoute method of the Routes object in the Global.asax file. In this article, focus is on single-project area support.
To get started with the areas, right-click your project's main node in Solution Explorer, and select the Add/Area command from the popup menu. This will open a dialog box asking for the name of your new area (Figure 2). Unlike with controller names, you don't need to append the word "Area" to the name, but you can if you prefer. However, bear in mind that intra-project areas will be accessed using the default route of /areaname/controllername/action/id. Because of this, you might not want to suffix the word "Area". In this article however, the word "Area" is appended for clarity.
Figure 2. When adding an area, you must give it a name.
Once you have created your area, Visual Studio will add a
new folder called "Areas" in your project (Figure 3). This
folder will contain a sub-folder with the name of your area,
and inside that you will see a familiar layout of folders
for controllers, views and models. In fact, you would add
controllers, views and models to this area folder just the
same as you would add them to your "master" MVC project. All
in all, an area is like a mini MVC application inside
another. Note also the
file. This file's definitions are referenced to from the
Figure 3. Areas occupy their own folder inside your project.
Areas can be used in multiple ways. Because they are
directly accessible using the previously mentioned default
route, you can utilize them like any other link inside your
application. Or, if you had an area controller action that
would return a snippet of HTML code to be used inside a
larger HTML page (a normal view page), you could use the
HtmlHelper.RenderAction method as follows:
Notice how there's an anonymous object being used to specify which area you want to use. Because areas can be completely independent of the master project, you can easily create usable parts or building blocks from your MVC applications and then combine them into larger solutions.
Area support is a very welcome addition to the framework. Luckily to us developers, area support is by no means the only new feature in ASP.NET MVC 2, like the next sections show.
Handling posts and encoding
When you need to handle form posts in your MVC applications, you generally write a new, overloaded controller action method to process the submitted data, and store it for example in a database. Since you only want these methods to be called using the HTTP protocol POST verb, you add an attribute at the beginning of the method like this:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult MyAction(MyObject data) ...
Although there's nothing wrong in the
AcceptVerbs attribute, ASP.NET MVC 2 allows you
to achieve the same thing with a shorter attribute
[HttpPost] public ActionResult MyAction(MyObject data) ...
Even though this is a small improvement, it is very likely that all MVC developers give it a warm welcome. Another useful new improvement is the support for automatically encoded output tags in view pages. Strictly speaking, this is not a new ASP.NET MVC feature, but instead a feature in ASP.NET 4.0. Even so, this new tag type is especially useful in MVC applications.
To illustrate the new tag, consider the following very common need to encode output for HTML:
<%= Model.CustomerName %>
This is a very simple tag, and works well in many situations. However, if the customer name were to contain certain special characters, you would need to encode the output to avoid user interface mess-ups and cross-site scripting attacks. A straightforward MVC method would do the trick:
<%= Html.Encode(Model.CustomerName) %>
All these ways to encode output are not inconvenient, but
a shorter syntax would be great. This is what the nifty new
code block" tag does:
<%: Model.CustomerName %>
Notice the colon (:) immediately after the opening tag.
It is a new way to encode output. The old equal sign syntax
(which itself is a shortcut for
is not going away. You can continue to use the old way, but
the colon-syntax encoding is there to make the view page
Note that at this writing, you cannot use ASP.NET MVC 2 RC within Visual Studio 2010 Beta 2. Thus, you cannot effectively use this combination to test these code block tags, but you can test them in regular ASP.NET 4.0 applications (or with the older MVC Beta 2).
Using lambda expressions with the HtmlHelper object
If you have used ASP.NET MVC 1.0, then you've most probably also created a model object and enabled editing of its details with HTML code similar to the following:
<%= Html.TextBox("Name", Model.Name) %>
Although this is fine for many purposes, the problem is that you still have to enter a string constant. Because it is a string, the compiler will not complain if you later change the property name in the model class, but forget to change the HTML tag. Also, the syntax is somewhat verbose (at least to some developers), and requires you to manually create one field per model object property.
In ASP.NET MVC 2, you can use the new
TextBoxFor method. Just like the previous
HtmlHelper methods like
ListBox, and so on, there are now multiple
*For methods that all accept a lambda
expression returning the correct object value.
Thus, to create a new editing control for the Name property, you could write code like this:
<%= Html.TextBoxFor(c => c.Name) %>
Here, the lambda expression parameter "c" is replaced at runtime with the model object instance, and in addition to getting rid of the string value, you will get full IntelliSense support just like before with the model object.
ASP.NET MVC 2 also brings support for a convenient way to create editing forms for complex objects quickly. For instance, if you had a model object with three fields, you could either manually create labels and text boxes for each of the three fields, or use a new extension method called EditorForModel. This method will create form fields for each visible property in the model:
<%= Html.EditorForModel() %>
This method is really convenient, if you don't have special formatting requirements for your editing forms.