We have made a long journey from classic ASP to ASP.NET. But the journey is far from over. ASP.NET framework introduced code behind model which eliminated the spaghetti code written in classic ASP. Although the code behind model made the life of an ASP.NET developer comfortable but it was far from being perfect. The biggest drawback was not able to test the code written in the code behind. The model was also dependent on the ViewState and Postback which introduced many other issues related to web programming. Recently, Microsoft released the CTP version of the ASP.NET MVC framework that solves some of these issues. In this article we are going to take a look the different aspects of the MVC framework by creating a small application.

Introduction:

We have made a long journey from classic ASP to ASP.NET. But the journey is far from over. ASP.NET framework introduced code behind model which eliminated the spaghetti code written in classic ASP. Although the code behind model made the life of an ASP.NET developer comfortable but it was far from being perfect. The biggest drawback was not able to test the code written in the code behind. The model was also dependent on the ViewState and Postback which introduced many other issues related to web programming. Recently, Microsoft released the CTP version of the ASP.NET MVC framework that solves some of these issues. In this article we are going to take a look the different aspects of the MVC framework by creating a small application.

Download ASP.NET 3.5 Extensions:

In order to use the MVC framework you will need to download the ASP.NET 3.5 Extensions. You can download the extension here.

Application Scenario:

I will keep the application very simply so you can absorb the basics of the ASP.NET MVC framework. The application will display a list of categories when a particular category is clicked it will show all the articles contained in that category. Finally, you can view the complete article by clicking on the particular article.

Database Design:

We will only be using two tables from the database, Categories and Articles. Take a look at the image below: 


 
ASP.NET MVC Project Template:

Once, you have downloaded and installed the ASP.NET 3.5 Extensions you will be able to utilize the ASP.NET MVC Project. From the project templates choose ASP.NET MVC Project. When the project is created you will see some new folders added to your project.

Content: Used to store .CSS files, images etc.
Controllers: This folder contains all the controllers in the application
Views: This folder contains all the views of the application
Shared: Contains items which can be shared in an application

Now that we have the basic idea about the folders included in our application we can get started.

Displaying Categories on the Page:

Let’s start by displaying categories on the page. First, you need to add a controller “CategoriesController” inside the controller folder. The CategoriesController will be responsible for invoking and rendering the correct view. Here is the implementation of the “CategoriesController”.

public class CategoriesController : Controller
    {

        [ControllerAction]
        public void Index()
        {
          
        }

        [ControllerAction]
        public void List()
        {
            var categories = CategoryRepository.GetAll<Category>();
            RenderView("Categories", categories);
        }

      
    }

The methods Index and List are decorated with the ControllerAction attribute. This means that both of them will serve as actions of the controller. If you type http://localhost:6701/Categories then the Index action is triggered. Currently, we don’t have anything in the Index method so it won’t do anything. If we type http://localhost:6701/Categories/List then the List action is triggered which retrieves all the categories from the database and render the “Categories” view.

You can change the URL format of the application by changing it in the Global.asax file. We will take a look at it later in this article.

We are passing two parameters to the RenderView method. One is the name of the view that we would like to be rendered and the second is the data that we need to pass to the view which in this case is the categories collection.

Here is the implementation of the “Categories” view.

<div>
   
    <% foreach (var category in ViewData)
       {
          
      %>
     
      <li>
      <%=  Html.ActionLink(category.Title, new { controller = "Articles", action = "List", category = (category.Title.Replace(".","_")) }) %>
      </li>
      
       <% } %>
   
    </div>

Here is a screen shot of the page which list all the categories.

 

Displaying Articles of a Category:

So, far we have managed to display all the categories on a page. Now, let’s see how we can display all the articles related to a category. Our target is to create a URL like the following:

http://localhost:64701/Articles/List/Client%20Side%20Development

The URL clearly shows that the articles are related to the Client Side Development category. For this to work we need to add a custom route to the route collection. This is performed in the global.asax file. Take a look at the following code which adds a new route:

protected void Application_Start(object sender, EventArgs e)
        {
            // Note: Change Url= to Url="[controller].mvc/[action]/[id]" to enable
            //       automatic support on IIS6

            RouteTable.Routes.Add(new Route
            {
                Url = "Articles/List/[category]",
                Defaults = new { controller = "Articles", action = "List", category = (string)null },
                RouteHandler = typeof(MvcRouteHandler)
            });

            RouteTable.Routes.Add(new Route
            {
                Url = "[controller]/[action]/[id]",
                Defaults = new { action = "Index", id = (string)null },
                RouteHandler = typeof(MvcRouteHandler)
            });

            RouteTable.Routes.Add(new Route
            {
                Url = "Default.aspx",
                Defaults = new { controller = "Home", action = "Index", id = (string)null },
                RouteHandler = typeof(MvcRouteHandler)
            });


        }
    }

The route in the bold is the new route. The new route indicates that when URL Articles/List/[category] is entered it will invoke the List action of the ArticlesController passing the category as the parameter.

Now, let’s check out the List method of the ArticlesController.

[ControllerAction]
        public void List(string category)
        {
            var articles = ArticleRepository.GetByCategoryName(category.Replace("_","."));           
            RenderView("Articles",articles);
        }

As, you can see the List action takes the category as the parameter and uses it to retrieve all the articles from that category. Later, the “Articles” view is rendered. 

 

Displaying the Article:

Finally, let’s take a look at how we can display the article on the page. We are going to choose the following URL format to display the article.

http://localhost:64701/Articles/Details/180

This means that we are displaying the article with the ID equal to 180. This might not be the best way to display the article since it will not easily indexed by the search engines but let’s try to keep things simple for this article.

Here is the code for the Articles view.

<% foreach (var article in ViewData)
       {
          
      %>
     
      <li>
      <%= Html.ActionLink(article.Title, new { controller = "Articles", action = "Details", id = article.ArticleID }) %>
      </li>
      
       <% } %>
   
    <%= Html.ActionLink("Back to categories",
        new { controller = "Categories" ,action = "List" }) %>

The link sends a request to the Details action of the ArticlesController passing the ArticleID. We have also placed a link to “Back to Categories” page just for fun!

Finally, the Details view displays the article.

  <div>
   
    Title: <%= ViewData.Title %>
    <br />
    Abstract: <%= ViewData.Abstract %>
    <br />
    Description: <%= ViewData.Description %>
   
    <%= Html.ActionLink(ViewData.Category.Title, new { controller = "Articles", action = "List", category = ViewData.Category.Title })%>
   
    </div>

Conclusion:

In this article we looked at the Microsoft ASP.NET MVC Framework. The framework allows us to break down the application into finer layers which results in better maintenance. Using MVC framework we can also unit test our views and controllers which was very hard to achieve using the code behind model.

In the future articles we will cover URL rewriting, testing and other cool stuff. I hope you liked the article happy coding!