Published: 20 Feb 2008
By: Kazi Manzur Rashid
Download Sample Code

Learn how to develop a Digg-like application with ASP.NET MVC, LINQ to SQL and ASP.NET AJAX.

Introduction

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:

[Live Demo]

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.

Prerequisites

A brief Introduction to the ASP.NET MVC Framework by Scott Guthrie:

An excellent Screencast by Scott Hanselman.

Overview

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:

  • Model,
  • View,
  • Controller.

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

images/mvc.jpg

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

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 the others.
  • Pretty/SEO (Search Engine Optimization) URLs. Full controls of how URLs are constructed. No need to do URL Rewriting anymore.
  • 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.

Request Flow

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

images/request.jpg

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

Default Conventions

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 match the 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, Stylesheets, JavaScript files and so on.

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

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 Controllers:
  • 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 StoryController:

And the following code snippet shows the action methods of UserController:

Note that the Action methods are declared as public and Marked with the ControllerAction attribute. In future versions of ASP.NET MVC the attribute will no longer be needed. Publicly declared method will automatically become the action methods.

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 with a .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 Story/[action], [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: [controller] and [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

FunctionalityUrl FormatControllerAction
LoginUser/LoginUserControllerLogin
SendPasswordUser/SendPasswordUserControllerSendPassword
SignupUser/SignupUserControllerSignup
LogoutUser/LogoutUserControllerLogout
List All Published StoryStory/Category
Story/Category/[page]
StoryControllerCategory
List Published Stories for a specific CategoryStory/Category/[categoryName]
Story/Category/[categoryName]/[page]
StoryControllerCategory
List Upcoming StoriesStory/Upcoming
Story/Upcoming/[page]
StoryControllerUpcoming
List Stories for a specific TagStory/Tag/[tagName]
Story/Tag/[tagName]/[page]
StoryControllerTag
List Stories Posted By an UserStory/PostedBy/[userName]
Story/PostedBy/[userName]/[page]
StoryControllerPostedBy
Search StoriesStory/Search?q=query
Story/Search/[q]/[page]
StoryControllerSearch
View Details of a StoryStory/Detail/[storyID]StoryControllerDetail
Submit a StoryStory/SubmitStoryControllerSubmit
Vote a StoryStory/KiggStoryControllerKigg
Post a CommentStory/CommentStoryControllerComment

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: isSuccessful and 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 UserController and 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 web.config.

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.

Summary

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.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Kazi Manzur Rashid

Kazi Manzur Rashid, Nickname Amit is a Diehard fan of Microsoft Technology. He started programming with Visual Basic 5.0 back in 1996. Since then he has developed many diversified solutions in his professional career, which spans from Anti-Spyware Tool to Personalized Start Page. Currently He is wor...

This author has published 10 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
jQuery Mobile ListView
In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
Exception Handling and .Net (A practical approach)
Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
JQuery Mobile Widgets Overview
An overview of widgets in jQuery Mobile.
Book Review: SignalR: Real-time Application Development
A book review of SignalR by Simone.

You might also be interested in the following related blog posts


MvcContrib working on Portable Areas read more
ASP.NET MVC and the templated partial view (death to ASCX) read more
Software Design Best Practices Debate read more
Tell Me Your Unit Testing Pains read more
Avoid Using a Database as an API Integration Point read more
Web Parts in SUB V2 read more
Keep Writing SharePoint Web Parts Until (at least) 2006 read more
Top
 
 
 

Discussion


Subject Author Date
placeholder Great Tanzim Saqib 2/20/2008 3:28 AM
RE: Great Kazi Manzur Rashid 2/23/2008 8:43
placeholder Nice Article Can be better!!! Khushal Patel 2/20/2008 7:07 AM
RE: Nice Article Can be better!!! Simone Chiaretta 2/20/2008 8:35 AM
placeholder RE: RE: Nice Article Can be better!!! Kazi Manzur Rashid 2/20/2008 9:05 AM
RE: RE: Nice Article Can be better!!! Kazi Manzur Rashid 2/20/2008 9:11 AM
placeholder Trouble with URL Courtney Bearse 2/20/2008 9:36 AM
RE: Trouble with URL Kazi Manzur Rashid 2/20/2008 2:29
placeholder Good piece of work Foong W.K. 2/23/2008 1:50 AM
RE: Good piece of work Kazi Manzur Rashid 2/23/2008 8:44
placeholder Excellent Kenneth Solberg 3/14/2008 2:55 AM
Mix Relase Sonu Kapoor 3/14/2008 11:37 AM
placeholder RegisterRoutesForOldIIS Gyan Singh 5/9/2008 5:45 AM
When is part 2 or 3 John Chen 3/9/2009 2:49

Please login to rate or to leave a comment.