ASP.Net MVC Routing With Examples

This post covers how routing is done in ASP.Net MVC applications, We will cover different aspects of routing with the help of examples. RouteConfig.cs present in the MVC Application does all the magic.

Let's dive deep into this little lake of MVC Routing.


What is Routing in ASP.Net MVC?


Traditionally Web applications used to work for a specific URL which points to a particular page/resource physically present on the server. However in case of MVC application the URLs are made in such a manner that they point to specific controller action. MVC framework map these logical URLs to judge which action of which controller needs to be called. From MVC 5 Microsoft has introduced new feature of "Attribute Routing" which much more advanced than the traditional routing mechanism. Learn more about "Attribute Routing" in another post.

Why we need Routing?


Take an example of this ugly looking URL
www.xyz.com/account/registeruser.aspx?userid=111
Isn't it better like this
www.xyz.com/account/registeruser/111

Routing gives us so many advantages, lets have a look at those
  • Clean & Beautiful URLs
  • URLs are SEO friendly
  • URLs are descriptive of user actions and thus much helpful
  • Needn't to have a physical file present with the same name as of URL
  • No need of query-strings

What is RouteConfig.cs?


ASP.Net uses RouteConfig.cs to understand the routes defined by the developer so as to cater different route requests. Shown below is snippet from RouteConfig.cs which is found at ~/App_Start/RouteConfig.cs in your application.


public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

All the routes are defined here and .Net framework makes it easy for us by creating a default route.
As shown there's a RegisterRoutes(RouteCollection routes) method which is called at ApplicationStart() in global.asax.cs. Method has a 'routes' parameter which is then mapped with default route by using routes.MapRoute() method.


As shown if user enters URL in format "domain/X/Y/Z" then the framework will interpret X as controller name, Y as action name and Z as Id parameter as mentioned in the route. However if user just enters URL as "domain" then system will interpret it as Index action of Home Controller because this is mentioned in the route defaults

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

UrlParameter.Optional specifies that the wildcard {id} is not mandatory and if user doesn't passes the value for id then also its okay for the routing system.
We can also alter these defaults to our specific controller or action name.



How To Create Custom Routing Using routes.MapRoute?


If you want to create a custom route where you can specify your default controller and actions, there are two ways:
Either you can alter the "Default" route, or you can create a separate route and let "Default" route handle the unhandled routes.

So, to add another route we simply use routes.MapRoute to add another route with name as per your wish. Let's take an example for a controller named "Account" and there's an action named "User" which returns user info on the basis of Id.

routes.MapRoute(
    name: "Account",
    url: "Account/{userid}",
    defaults: new { controller = "Account", action = "User", id = UrlParameter.Optional }
);


Here we have made a route in which you need not to provide action name and Id will also be accepted without creating a querystring in path. Here in this route we have mentioned that if the path starts with /Account followed by a userid parameter then Controller for that request is "Account" and Action will be "User". So it will cater the request for

www.xyz.com/Account/111

namespace MVCApp.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult User(int userid)
        {
            return View();
        }
    }
}

Here the routing mechanism is so smart that it will convert the value of userid parameter to whatever type action is expecting. So here it will convert the value of userid to int, if it is unable to do that, it throws an error for this request www.xyz.com/Account/abc

 The parameters dictionary contains a null entry for parameter 'userid' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult User(Int32)' in 'MVCApp.Controllers.AccountController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.


So this way you can create your custom routing with any input instruction and any number of parameters.
That's all about Traditional Routing technique in MVC. You can read about "Attribute Routing" in our next post.

Please let us know did you find it helpful?

Happy Learning!!!

Comments

  1. The blog gave me idea about routing in Asp.Net My sincere thanks for sharing this post and please continue to share this post
    Dot Net Training in Chennai

    ReplyDelete

Post a Comment

Hey there, liked our post. Let us know.

Please don't put promotional links. It doesn't look nice :)

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example