6 min read

(For more resources on .NET, see here.)

As of now, the ASP.NET MVC framework is still in CTP (Community Technology Preview, which is similar to an advanced pre-stage), and there is no certain date when it will be released. But even with the CTP 5, we can see how it will help MVC applications follow a stricter architecture. We will quickly see how to use the ASP.NET MVC framework through a small example.

Sample Project

First, download the ASP.NET MVC framework from the Microsoft website and install it. This installation will create an MVC project template in VS 2008.

Start VS 2008, select the File | New Project menu item and then choose theASP.NET MVC Web Application template to create a new web application using this template.

ASP.NET MVC Framework

There are many free unit testing frameworks available for ASP.NET projects, and NUnit and MBUnit are two of the most popular ones. Here are the links:

MBUnit: http://www.mbunit.com/
NUnit:; http://www.nunit.org/index.php

ASP.NET MVC Framework

Select the default option and click OK. You will notice that two projects have been added to the solution that VS has created. The first project is a web project where you’ll implement your application. The second is a testing project that you can use to write unit tests against.

ASP.NET MVC Framework

In our custom MVC code project, we had different projects (class libraries) for the model, the view, and the controllers. The default directory structure of an ASP.NET MVC Application has three top-level directories:

  • /Controllers
  • /Models
  • /Views

When the project becomes large, it is recommended that the Model, Views and Controllers are put in separate class library projects of their own so that it’s easy to maintain them. But for the purpose of illustrating the ASP.NET MVC framework, this default structure is fine for us.

We will create a simple customer management application. For this, we first create some ASPX pages in the Views folder. Note that VS has already created these subfolders for us, under Views:

  • Home: Contains the and Index views
  • Shared: Contains shared views such as master pages

Before we go on to adding custom code in this project, let us understand what VS has done for us while creating this MVC project.

URL Routing Engine

In the standard ASP.NET model (or Postback model), the URLs map directly to the physical files:

ASP.NET MVC Framework

So when we make a request to a page, say MyPage.aspx, the runtime compiles that page and returns the generated HTML back to IIS to be displayed by the client browser. So we have a one-to-one relationship between the application URLs and the page.

But in the MVC framework, the URLs map to the controller classes.

ASP.NET MVC Framework

Therefore, the URL is sent to IIS and then to ASP.NET runtime, where it initiates a controller class based on the URL, using the URL routes, and the controller class then loads the data from the model, with this data finally being rendered in the view. The controller classes uses URL routing to map the URLs, which in simpler terms means rewriting URL. We can set up the rules for which URL is to be routed to which controller class. The routing will pick up the appropriate controller and pass in the query string variables as necessary. Open the global.asax.cs file and examine the following code:

public class GlobalApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapRoute(
“Default”, // Route name
“{controller}/{action}/{id}”, // URL with parameters
new { controller = “Home”, action = “Index”, id = “” }// Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}

The RegisterRoutes() method contains the URL mapping routes. Initially we have only the default rule set:

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);

The RegisterRoutes() method contains the URL mapping routes. Initially we have only the default rule set:

The MapRoute() method, which handles URL routing and mapping, takes three arguments:

  1. Name of the route (string)
  2. URL format (string)
  3. Default settings (object type)

In our case, we named the first route “Default” (which is the route name) and then set the URL as:

Controller/action/id

The Controller here is the name of the controller class. action will be the method that needs to be invoked inside that controller class. id would be the parameters that need to be passed, if any.

In the default arguments, we create a new object and call it “Home”, set the action to Index, and do not pass parameters to it. Note the new anonymous type syntax used to create parameter defaults:

new { controller = "Home", action = "Index", id = "" }

The var keyword and anonymous types: We normally use classes to wrap behavior and properties, but in C# 3.0, we can create the types anonymously without needing to create classes for them. This can be useful when we need to create light weight classes that have only read-only properties. We can use the anonymous syntax to create those types without the need to create a class for them. We can use the new “var” keyword to hold such anonymous types, for example: var ch = new { readOnlyProperty1 = value1, readOnlyProperty2 = value2 };

It is important that we name and assign a value to each of the properties that we are creating. What will be the type of the properties? They will automatically be cast to the data types of the values of the properties specified. The anonymous types will always be derived from the base object class directly. They can only be used within class members and cannot be passed as method arguments (unless they are boxed), return values, or be specified as class-level variables. Once the type is created, it cannot be changed into another type.

So we create a new anonymous type as the last argument of the MapRoute() method, passing in variable defaults with three properties, namely controller, action, and parameter.

Now have the Default.aspx page under the root directory, which acts as a redirecting page to the main home page of the site (which is /View/Home/Index.aspx). We cannot directly set that as the “default” page since we are using URL routes to process pages instead of using physical files in the URLs. So in the code-behind of our Default.aspx page, we have a simple redirect:

public void Page_Load(object sender, System.EventArgs e)
{
Response.Redirect("~/Home");
}

So the runtime will first set up routes in the global.asax page, then it will process the Default.aspx page. Here it faces a redirect to this URL: /Home.

The Controller

The MVC framework maps this URL to the route set in the global route table, which currently has only the default one, in this format:

Controller/action/id

So /Home corresponds to a controller named Home, and because we have not specified any action or ID, it takes the default values we specified in the RegisterRoutes() method in the globals.asax.cs. So the default action was Index and the default parameter was an empty string. The runtime initializes the HomeController.cs class, and fires the Index action there:

public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}}

In this Index() method, we set the data to be displayed in the View (aspx/ascx pages) by using a dictionary property of the base Controller class named ViewData. ViewData, as the name suggests, is used to set view-specific data in a dictionary object that can hold multiple name/value pairs. When we call the View() method, the ViewData is passed by the Controller to the View and rendered there.


Subscribe to the weekly Packt Hub newsletter

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here