Click here to Skip to main content
Click here to Skip to main content
Go to top

Controllers and Routers in ASP.NET MVC 3

, 2 May 2011
Rate this:
Please Sign up or sign in to vote.
A deeper look into the two pillars of ASP.NET MVC – Routers and Controllers.

Introduction

ASP.NET MVC provides a new way of creating web applications which is more extensible and testable. We discussed about ASP.NET MVC in Introduction to ASP.NET MVC 3. Here, we will have a deeper look into the two pillars of ASP.NET MVC – Routers and Controllers.

Routers

One of the main objectives of ASP.NET MVC is Search Engine Optimization (SEO). Search Engines work mainly using URLs. Defining a meaningful and more understandable URL is very important to make our application more search engine friendly.

Routing is the way of constructing meaningful URLs for a web request. As you have already seen, our MVC application URLs are not represented by extensions like .aspx. Instead, the URLs consist of the Controller name and Action name.

Let us first understand how the default routing works. Open the Global.ascx file, and we can see the Application_Start() and RegisterRoute() methods.

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 = UrlParameter.Optional } 
            // Parameter defaults
    );
}

Look at the statement where we map the routing. Our URL formation uses the pattern “{controller}/{action}/{id}", where id is an optional parameter.

new { controller = "Home", action = "Index", id = UrlParameter.Optional } specifies that in case the URL does not specify a Controller, use the Home Controller. Also, in the absence of an Action, it uses the Index action, and the last parameter is Optional.

Routing data inside a Controller

We can access routing data inside a Controller using the RouteData object.

public ActionResult Index()
{
    ViewBag.Message = string.Format("{0}---{1}--{2}",
        RouteData.Values["Controller"],
        RouteData.Values["action"],
        RouteData.Values["id"]
        );
            
    return View();
}

Controllers

Now let us create a new Controller and see how we can route to the new Controller using a different routing pattern.

Add a new Controller using Add New Item -> Controller. It adds a new Controller with an Action as Index. For our sample application, we are using a different Action called Verify.

public class SampleController : Controller
{
    //
    // GET: /Sample/
 
    public ActionResult Verify()
    {
        return View();
    }
}

As there are no Views corresponding to SampleController, let us return some text from our Action. For returning any text data from an Action, use the Content class.

public ActionResult Verify()
{
    return Content("Hello From Sample Controller.");
}

Let us run the application. Modify the URL to /sample/verify.

But if we specify /Sample without any Action, we will receive a 404 error. As per the defined routing, if there is no Action specified, it should redirect to the Index action inside the specified Controller. Here, our SampleController doesn’t have any Index action and throws an error.

Adding a new route

For fixing the above issue, let us define a new route called “sample”.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
                "sample",
                "Sample/{action}",
                new { controller = "Sample", action = "Verify" }
                );

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

}

Now we may need to pass some data to our new Controller from a URL, like the id parameter in the default routing. For that, define a new parameter in the routing.

routes.MapRoute(
                "sample",
                "Sample/{username}",
                new { controller = "Sample", action = "Verify" }
                );

The value can be accessed either using the RouteData object or through a parameter to the Verify action.

public ActionResult Verify(string username)
{
    return Content(username);
}

Note that the URL consists of only the Controller and the parameter.

Again, you will receive a 404 error when we omit the parameter value.

For solving this issue, we need to specify the default value for the username parameter either in the Route mapping or in the Controller.

In the route map, specify the parameter as optional.

routes.MapRoute(
                "sample",
                "Sample/{username}",
                new { controller = "Sample", action = "Verify", 
                      username=UrlParameter.Optional }
                );

Inside the Controller, specify the default value for the parameter.

public ActionResult Verify(string username="all")
{
    return Content(username);
}

Conclusion

We had a quick discussion on how routing works in ASP.NET MVC and how we can customize the same. We will discuss more about Views, Styles, Action results, etc., in the next article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ambilykk
Architect TCS
India India
I have over 10 years of experience working on Microsoft Technologies. I am carrying the passion on Microsoft technologies specifically on web technologies such as ASP.Net, HTML5, jQuery and Ajax. My interests also include TFS, Azure, Windows 8, Visual Studio 2010. Technology adoption and learning is my key strength and technology sharing is my passion.
 
Microsoft MVP: Connected Service Developer
Follow on   Twitter   LinkedIn

Comments and Discussions

 
Questionhow can I get a list of all controllers and the action inside each of these controller and create a view out of it? PinmemberMember 807057121-Aug-13 4:10 
QuestionMy vote 5 Pinmemberharshal76896-Aug-13 19:43 
GeneralMy vote of 5 PinprofessionalAntariksh Verma24-Jul-13 0:55 
QuestionThis article is very helpful for understanding about routing. I have a doubt on Dynamic routing [modified] PinmemberRajeesh8118-Apr-13 8:52 
GeneralMy vote of 5 Pinmembervaibhav10Dec198715-Mar-13 1:52 
GeneralMy vote of 5 Pinmembermanoj kumar choubey16-May-12 21:20 
General5 Points From Me Pinmembersobo12323-Dec-11 21:58 
GeneralMy vote of 5 Pinmemberaeonjake19-Jun-11 7:24 
GeneralMy vote of 5 PinmemberMember 201025622-May-11 20:27 
GeneralGreat Explanation PinmemberRabb Moshe Plotkin9-May-11 18:14 
GeneralRe: Great Explanation Pinmemberambilykk10-May-11 1:14 
GeneralMVC Pinmembertjstickel9-May-11 11:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 2 May 2011
Article Copyright 2011 by ambilykk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid