I must say that being able to use the Routing engine in ASP.NET MVC is liberating.  In the traditional web model, your browser is making a request for a file on some remote web server.  The server looks for that file, processes it, and makes a response.  This model works great, but what if you don’t want “.aspx” on the end of your Url?  Beyond that, relative paths on the server can take away from any readability your Urls may have had.  Ever tried explaining query string parameters to the average user?  Painful.

Routing isn’t a new thing by any means, but has recently become a reality in the world of .NET.  There’s a whole namespace dedicated to it in System.Web.Routing.  It allows you to create cognitive, user friendly, and meaningful Urls.  Time for an example.

Sam is on a project, and his program manager instructs him to create a user profile page for their application.  With some special permission, Sam is able to try out ASP.NET MVC.  Does he start coding at the drop of a hat?  Never.  Ever.  Requirements first!  One of the general requirements says “The average user knows what page the Url represents.”  Sam is a good programmer, so his gut reaction is a question: “How would the user know that a Url points to their own profile?”  He writes out on his whiteboard (because all good programmers write things out on a whiteboard):

Traditional ASP.NET Web Forms Way:

http://localhost:1234/Users/UserProfile.aspx?UserID=1&Username=johncoder
http://localhost:1234/Users/UserProfile.aspx?UserID=1

Ideal Ways in ASP.NET MVC:

http://localhost:1234/Users/1/johncoder
http://localhost:1234/Users/1
http://localhost:1234/Users/johncoder <- Possible naming conflicts, but previous two work fine.

Now that Sam knows how he wants to accomplish his goal.  He fires up Visual Studio and creates a new ASP.NET MVC Web Application.  He uses his company’s existing data access layer, which uses LINQ to SQL classes.  Routes point to Action Methods on Controllers, which means that Sam needs a UsersController:

public class UsersController : Controller
{
    public ActionResult Details(int id)
    {
        UserRepository repository = new UserRepository();
        User user = repository.FindUserById(id);
        return View(user);
    }
}


The Details Action Method finds the target User, and a View for the user model.  By default, it will use “Views\Users\Details.aspx”.  There’s more!

public class MyMvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = "" }
        );
    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}


The above code appears in the Global.asax.cs file an MVC application by default.  “Default” is the name being assigned to this given route, and “{controller}/{action}/{id}” is the Url.  The anonymous object in the next line serves as the default values for this route.  Using this route, the Url to a user would look like this:

http://localhost:1234/Users/Details/1

This isn’t quite what he had in mind.  Sam needs to create a new route to facilitate his need.  Here’s what he came up with:

routes.MapRoute(
    "UserProfile",
    "Users/{id}/{username}",
    new { controller = "Users", action = "Details", username = "" }
);


There's a little trickery going on here. Notice that he made no mention of a controller, or even an action method in the Url. Instead, he is taking advantage of the default parameter values by using an anonymous type. Since he didn’t include “{controller}” in his Url, the anonymous object needs to specify which controller to use.  MVC is built to look for "controller" and "action" keywords, and allows you to add your own. In this case, he added "id" and "username" parameters. If the user does not specify an "id" value, the request will not match against this route, and continue searching the RouteCollection until it finds a match.  Since he specified a default “username” as an empty string, the user is not required to enter a username.  The Url in this route has “Users” hard coded into it.  That literally means that the Url has to have “Users” in it.

Another feature of the Routing engine is that it can be used to generate Urls, too.  Sam can change any View in his application to use an HtmlHelper method like so:

<%= Html.RouteLink(user.FullName, "UserProfile", new { id = user.Id, username = user.Username } ) %>


The first parameter is the anchor text. The second is the name of the Route that the engine should use. The properties of the anonymous object are the parameters in the Url.

Don’t you agree that this is much more flexible than relying on the file system to create Urls?  It is my honest opinion that attention to usability details (even as transparent as a Url) produces a professional, high quality product.  By taking advantage of newer features, like the Routing engine, we can escalate our standards to the next level.

Thursday, October 08, 2009 12:11:37 AM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] -
ASP.NET MVC | C# | Routing | Usability

John Nelson

mugshot I am a passionate C# Developer working in ASP.NET on an e-commerce solution for ticketing software. I work across all of the application layers, including server side functionality, and client side programming with jQuery and MS Ajax. Although my full time job is in WebForms, I spend many of my off hours working with MVC. I am especially interested in productivity and good programming practices.

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
John Nelson
Statistics
Total Posts: 25
This Year: 3
This Month: 1
This Week: 0
Comments: 1