Routes, Actions and Action Results

Routes and Actions

A couple tutorials before this we saw the following explanation of a url:

A screenshot of the a typical MVC url

It would be instructive to look a little closer on how this is done. If you open up the global.asax file and take a peek at the code therein, you see the following:

    public class MvcApplication : 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);
        }
    }
    

TheMVCPatternMeetsASPNET gets mapped to the action of the same name on the GettingStarted controller because the use of the Url Routing library that Microsoft released recently. The most important line begins on line 6 above. The MapRoute command tells the routing library to intercept and route a url that fits the pattern specified. Since default values are supplied (line 9), to fit the condition of the routh a request does not need all three parameters.

Let's say someone entered the url http://www.howmvcworks.net/ into their browser, when the request hits the server, the routing engine will essentially fill in the defaults and try to execute the proper action. In this case it would fill in the controller as Home because that is the default value for the first segment (giving you http://www.howmvcworks.net/Home). It will then fill in the second default, which defaults the action Index in the second segment (giving you http://www.howmvcworks.net/Home/Index). It will then fill in the third default, which is a blank, for the third segment (giving you http://www.howmvcworks.net/Home/Index/). Given this routing configuration, then, all four url combinations when typed into the browser will end up with the same result, invoking the "Index" action on the "Home" controller. So what does that look like? Well, it looks like this:

        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
        }
    

The route above is just the default route created when a project is started. Further routes can be added, but that will be a discussion for another time. For now there are two crucial points that must be grasped. In the example above, the use of Home in the position that it is in routes the following action to the Home controller. Second, that action called Index is then invoked, and the proper response (like the rendering of a page) is made.

Action Results

So that is how a method on a controller gets invoked; it is called based on the Url. What the framework does once the method on the controller has been invoked is determined by the result of the method call. Those results are what are of the type ActionResult. ActionResult is itself an abstract class, and there are a number of different implementations of ActionResult. Here are a few of the action results that comes in ASP.NET MVC version 1:

A screenshot of the a typical MVC url

Each of these are a representation of the action that the framework is supposed to take in response to the browser request. If the request should return a view, a ViewResult is returned. If the request should return some Json, a JsonResult is returned. If the request should redirect, a RedirectResult is returned, and so on. If none of the built-in ActionResult derivatives meet your needs, you can always create your own. Some have already started doing that.

Others have begun creating their own custom action results. Here are a few:

ActionResult and the Expression of Intent

Before moving on, an important point must be made about the ActionResult class and its various derived classes, and that is that the ActionResult expresses the intent to perform an action, not the action itself. By instantiating a ViewResult class you are not actually creating a view; you are telling the framework to display a particular view. By returning a RedirectResult you are not redirecting the user; you are telling the framework to redirect them. Of course the framework respects your intent and shows the view, or redirects, or whatever.

This expression of intent rather than immediate execution is very important for making MVC applications and their controllers testable. By returning a result to express intent, a test can be written to check the result. For example, let us say you have a controller that will return a view for a logged in user but will redirect a user that is not logged in. By returning an ActionResult derivative, automated testing code can interogate the type of the ActionResult and can test that given certain inputs the controller responds one way and given other inputs it responds in another.

Speak Your Mind!

Have something to say? Find a grammatical mistake? Think I said something incorrect? Don't like my perspective? Hate my color scheme? Whatever it is, you can let me know. I would appreciate it if you did.