For the last few days, I have been trying to get my hands dirty with the new ASP.NET MVC framework. I saw many discussions on some of the
advanced topics like IoC Container/DI, View Engine, Controller factory and so on, but I could not find a simple application to harness the
power of the new ASP.NET MVC framework. Certainly, knowing these things is an added benefit but it is not mandatory to develop applications
with the ASP.NET MVC Framework. In this article - from the DotNetSlackers team - I will present a basic version of Digg / DotNetKicks kind of
application developed with the ASP.NET MVC framework. You will find the whole application running at the following link:
Note: The article and code are based on the first preview release of the ASP.NET 3.5 Extensions. We will be updating it as per
the new release.
A brief Introduction to the ASP.NET MVC Framework by Scott Guthrie:
An excellent Screencast by
The MVC (Model-View-Controller) is a popular pattern to
develop UI-centric applications based on a simple concept: divide the implementation into three logical components:
The ASP.NET MVC Framework is an implementation of the MVC pattern, and has built-in support for developing web applications. Let's
take a quick look at these three components.
Figure 1: The MVC Framework
- Model: Refers to the domain logic of your application. Usually the state of the Model is persisted in the database. Consider it
as the middle tier in a typical n-Tier application, which consist of the business logic and domain objects.
- View: Is typically the User Interface, which is used to show the Model data and take input from the User.
- Controller: Is responsible for handling the user interaction. This is the Ultimate Driver of the whole ASP.NET MVC Framework.
Depending upon the User gesture it decides which action to perform on the model; it also builds the view data and finally decides which View
The ASP.NET MVC Framework is an alternate and better way to develop web applications, comparing to the regular web form model. It
provides us with:
- Clean Separation of Concerns, where each component is serving only one purpose. Thus it also gives us the opportunity to
integrate TDD (Test-Driven Development) in the development workflow and unit test each component without considering the others, as most of
the framework components are interface-based. This allows us to mock them out.
- The whole framework is very much extensible and pluggable. It is really easy to replace or customize each part without affecting
- Pretty/SEO (Search Engine Optimization) URLs. Full controls of how URLs are constructed. No need to do URL Rewriting
- True stateless model of the web. We no longer have to deal with postbacks and ViewState.
- Full control of the generated HTML. This means no more naming containers.
- Utilize the existing knowledge of ASP.NET like Providers, Caching, Configuration and so on.
In regular ASP.NET web form applications, URLs are usually mapped to physical disk files. When a URL is requested, the code of the
associated file gets executed, which generates the HTML. However, in the ASP.NET MVC Framework the URLs are tied with the Controllers rather
than the disk file. The component that is responsible to map the URL with the Controller is the Routing Handler. When the application starts,
it is required to register the URL Routing Rules, which the Routing Handler uses to map the controller when the request arrives. Let's take a
quick view of how a request is carried in different layers of the ASP.NET MVC Framework:
Figure 2: The Request Flow
- The user requests a URL.
- The ASP.NET MVC Framework evaluates the requested URL against the registered Routing Rules and finds a matching Controller. The
Framework forwards the request to the matching Controller.
- The Controller calls the Model to build ViewData. It can call the model multiple times depending upon the ViewData that it is
- The Model, as mentioned earlier, is the middle tier, which might involve data access components, workflow activities, external
web service dependencies etc. The Model returns the requested data to Controller.
- The Controller selects a View and passes the data to the View which it previously got from the Model. The View Renders the data
and returns the generated HTML to the User.
There are few default conventions that we have to know before moving forward.
First, when matching the Controller for the incoming request, the framework uses a pattern UrlPathController to match the
Controller. For example, if the request is for http://www.example.com/Home, it will
HomeController for that request. Once the request reaches the Controller, the Controller executes a specified action
from the URL sub-path, or it executes the default action if the action is missing in the URL. The default action for a Controller is
specified when the URL Routing Rules are declared in the application start event handler. The actions are declared in the Controller class as
methods. For example, if the request is for http://www.example.com/Home/Index, it will automatically execute the
Index method of the
HomeController; and if the URL contains more sub-paths, it will pass each sub-path as a parameter value of that method.
Next, when creating an ASP.NET MVC Project in Visual Studio, it automatically creates Controllers, Models and Views folders. It is
recommended to create the Controllers, Models and Views in the corresponding folders. However, if you are developing a large application you
can choose to implement the Model in one or more different projects, but the Controllers and Views must be present in the MVC Project. For
each Controller, there should be a folder under the Views with the same name. For example, if we have a Controller named
HomeController, there should be folder named Home under the Views folder. If a single view is used by more than
one Controller, it should be placed under the Shared folder of the Views. The shared folder can also contain shared User Controls,
Philosophy and Functionalities of Kigg
Let us discuss the philosophy of Digg/DotNetKicks kinds of applications before moving to the implementation part. Both of these
applications are completely community driven. Members find an interesting Internet resource, they submit it to the application and it appears
instantly in the upcoming story queue. Other members can vote it, and once it reaches a certain number of votes, it appears in the front
The application will be able to:
- List all the published Stories.
- List the Stories by Category.
- List the Upcoming Stories.
- List Stories by Tag.
- List Stories Posted By an Individual User.
- Search Stories.
- View the Details of a Story.
- Allow user to Submit Story (Requires Login)
- Allow user to Kigg (Vote) Story (Requires Login)
- Allow user to post comment on a Story (Requires Login)
- Allow the Users to Login.
- Allow the users to Signup
- Allow the User to reset lost password.
Controllers and Actions Defined
- The functionalities of Kigg are Story and User related. Therefore, we can categorize these functionalities into two
StoryController: Handles all Story Listing, Searching, Submitting, Kigging etc.
UserController: Handles Authentication, Signup, Forgot Password etc.
When evaluating the Controller Actions, a good technique is to give the action a name similar to its functionality. The following
code shows the action methods of the
And the following code snippet shows the action methods of
Note that the Action methods are declared as
public and Marked with the
In future versions of ASP.NET MVC the attribute will no longer be needed. Publicly declared method will automatically become the action
Routing Rules Defined
Once the signatures of the Controllers are defined, it is time to declare the URL Routing Rules that will map the URLs to these
Controllers' action methods. As mentioned earlier, the Routing Rules must be registered in the application start event handler, in the
Global.asax file. When defining the Routing Rules, one thing you have to remember is keeping the most specific rule at the top.
It is similar to the try/catch block rule of exception handling, where we put the more general exception at the bottom and specific
exceptions at the top. If you open the
Global.asax file of this application, you will find that we have explicitly created two
methods to register these rules and call these methods in the application start event. The reasons behind creating these methods - instead of
registering them in the application start event - are that we do not want to clutter our rules with both newer and older versions of IIS.
When hosting an MVC application in IIS7 the URLs are extension-less, which is really cool, but in older versions of IIS the URLs are served
.mvc extension. So to support both older and newer versions of IIS we need to add the same URL, one with the extension
for the older version and another without extension for the newer version of IIS. Here, we are checking the
web.config for the
hosting IIS version and registering only the rules for that version. Another benefit of having explicit methods for registering the rules is
Unit Testing, which we will check in a few moments. The following code shows the Routing Rules Declarations:
As you can see, we are registering the most specific rules like User/Login, User/Signup, Story/Detail, Story/Category first and
least specific rules like
[controller]/[action] later. When mentioning the variables in the URL
format we are using
 to denote the variable. There are two fixed variable names in the MVC framework:
[action]. The others are simply the parameter names of the controller action methods. The last
rule, which maps to default.aspx to the all category is required to handle the /.
Test the Routing Rules
Once the Routing Rules and Controller signatures are defined, it's time to test the Rules, which will give us a clear idea on whether the
Rules are good enough to map the controller's action and if the correct parameter values are passed for a given URL. The following table
shows the test bed of Routing rules that we like to test:
Table 1: Tests
|List All Published
|List Published Stories for a specific
|List Upcoming Stories||Story/Upcoming|
|List Stories for a specific
|List Stories Posted By an
|View Details of a Story||Story/Detail/[storyID]||StoryController||Detail
|Submit a Story||Story/Submit||StoryController||Submit
|Vote a Story||Story/Kigg||StoryController||Kigg
|Post a Comment||Story/Comment||StoryController||Comment
You will find
Route.cs in the test projects folder, which is used to test the Routes. We have included both VSTSTest
and NUnit implementations of all the Unit Tests. For Mocking, we have used Rhino Mocks. The tests are done based upon the code that Phil Haack blogged few weeks ago in the post Testing Routes In ASP.NET MVC.
Here are few code snippets of the Routing Rule Test:
Implementing the UserController
Earlier, we defined the signature of the
UserController. Now it's time to add the actual implementation. The
UserController uses the ASP.NET Membership provider for login, signup and similar operations. The only difference between this
controller and the others is that all the methods of this controller returns JSON data instead of a regular HTML view. The controller methods
are called from the client side using the ASP.NET AJAX Framework. The following code shows the
Login method of this controller:
As you can see, we are creating a
JsonResult object at the beginning of the method.
JsonResult is a
simple class which has only two properties:
errorMessage, which denotes if the controller action
was successful. If the operation is not successful, it populates the
errorMessage with the proper reason. In the end, we are
passing the result as view data of the shared view called "Json". Since this is a shared view and it will be used by both
StoryController, we have placed it in the Shared folder under the Views. I am excluding
the other methods of this controller as they work almost the same as this. One important thing I would like to mention is that instead of
using the static Membership class directly in the code, we are passing the abstract membership provider in the constructor of this
controller. The reason behind this is that we can pass a Mock Membership Provider in our Unit Test, which we will check next. And in the
other constructor, we are passing the default membership provider, which is configured in the
Testing the UserController
For testing the Controller, we are also following the same test specific subclass pattern that Phil Haack blogged few weeks ago in the post Writing Unit Tests For Controller
Actions. As mentioned in the previous section, we will pass a Mock Membership Provider to test the controller. We will expect that the
proper method of the membership provider is called and that the controller is passing correct data to the view. The following code snippet
shows how the Login is performed for a successful attempt and how it fails when an empty user name is provided.
My initial intention was to provide all the details in a single article, but as you can see, the article has already evolved too much to
fit in a single part.
In this part, we took a brief overview of the ASP.NET MVC Framework and learned how to assign functionality to controllers, how to define
the routing rules and test them against URLs. We have also seen how to create a Controller that returns JSON data instead of regular HTML,
and tested the controller. In the next part, we will talk more about the Controller, which renders regular HTML view, using master pages and
user controls to create the view, passing strongly typed view data to the view and finally creating the Model. Stay tuned.