articles

Home / DeveloperSection / Articles / Introduction of Routing in MVC

Introduction of Routing in MVC

Anonymous User5776 21-Feb-2015

Hi everyone in this article I’m explaining about Routing in MVC.

Introduction:

Basically routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event. MVC5 also supports attribute routing.

Why use routing?

We are used to traditional web applications in which the URL the user enters in the browser maps to some specific physical file mapped to a directory on the web server which we call the virtual directory. That is why when we are developing an eCommerce application to sell products online we use URL's like http://www.example.com/electronics.aspx.

In traditional ASP.NET we have physical files on the application server's hard disk where it was hosted, that responds to the user's request. Whenever a user makes a request for a page, the ASP.NET Engine loads the page and tries to render it to the user's browser after following a full-fledged page life cycle. Since both the .aspx page and .aspx.cs file are tightly coupled, so whenever a request comes for a specific page, the ASP.NET Engines load both the .aspx and .aspx.cs files. This we can also state as the .aspx.cs file is the controller and the .aspx file is the view as in a traditional ASP.NET application. So it actually locates the physical file on the server's hard disk where it is hosted.

We'll try to demonstrate how the routing works in a MVC4 application. For that we'll use an example. Let's proceed with the example. I've named my application “UrlRoutingDemo” by selecting the “Basic” as the MVC4 project template.

Once the application is loaded in Visual Studio check in the Solution Explorer and we'll have a folder named “App_Start” that contains a file named “RouteConfig.cs”. The contents of which would be the default as in the following:

protectedvoid Application_Start()
{
            AreaRegistration.RegisterAllAreas();
 
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
}

It contains only one single function named RegisterRoutes that accepts a RouteCollection class object. One route is added to the RouteCollection object using the MapRoute function with the name “Default” (the one highlighted in yellow) also the pattern for the URL is specified as {Controller}/{action}/{id} where the default values for the controller and action are specified under the defaults named argument (which is the third parameter to the MapRoute function). Also for the id element the default value optional is specified. 

Let's try to understand this Route in depth. From the code snippet we can state that the route has the following 3 segments. 

  1. Controller Segment (which is defined as {controller})
  2. Action Segment (which is defined as {action})
  3. Parameter Segment (which is defined as {id})

We can also state that the default or optional values are provided for all the three segments. Like the Controller havs a default value of “Home”, the action has a default value of “Index” and id has an optional value. 

NOTE:

1-You can change the default values of the controller and the action method to any value of what your application requires. You can also add your own routing configuration in the RouteConfig.cs file as per your needs.

2-Also the name of the controller and the action method is not case sensitive. In other words, if the name of your Contoller is “Home” and in the routeconfig file you specified it as “home”. It will work.

This route can handle any request that has a maximum of 3 segments viz {controller}/{action}/{id}. It is basically a combination of default and dynamic route. The following table would explain the line as stated in a more concise manner. 

When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request to the appropriate controller and action. If there is no match in the route table for the incoming request's URL, it returns a 404 HTTP status code.

 

Introduction of Routing in MVC

 

In above example we have defined the Route Pattern {controller}/{action}/{id} and also provide the default values for controller,action and id parameters. Default values means if you will not provide the values for controller or action or id defined in the pattern then these values will be serve by the routing system.

Suppose your webapplication is running on www.example.com then the url pattren for you application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system. 

Let's try to add 2 controllers to the application. I named my first controller as “Home” and the second one as “Employee”. Here is the code snippet for both the files.

 

HomeController.cs:
publicclassHomeController : Controller
{
        //
        // GET: /Home/
 
        publicActionResult Index()
        {
            ViewBag.Message = "Index Function call from HomeController";
            return View();
        }
 
 }

 EmployeeController.cs: 

publicclassEmployeeController : Controller
{
        //
        // GET: /Employee/
 
        publicActionResult Index()
        {
            ViewBag.Message = "Index function call from EmployeeController";
            return View();
        }
 
}

 Both of them just contains the Index function that has a dynamic variable named Message of ViewBag that holds a certain value. And both of them are returning a view whose name is “Index”.

The following is the code snippet for the view “Index.cshtml”.

HomeController View:
@{
    ViewBag.Title = "Index";
}
 
<h2>Home Controller View</h2>
 
<h2>@ViewBag.Message</h2>

 

EmployeeController View:
@{
    ViewBag.Title = "Index";
}
 
<h2>Employee Controller View</h2>
 
<h2>@ViewBag.Message</h2>

 It just displays the message that comes from the controller.

If you run the application now, it will display the details for the “Home” controller (because of the routing configuration that set the default value of the controller to “Home” and action to “Index”). By looking at your browser's URL we can map this to the first row of the Table 1.0.

 URL Forming:

Suppose that your MVC website (or rather it could be an ASP.NET website also, for this we assume that you did URL Rewriting in ASP.NET) is being used in the market for a long time and the URL of your application has formed a contract with the user's. Because most users have a habit of bookmarking the URL that they visit often and now a days even the latest browsers store a tag of your website that the user has normally visited through that browser. In such cases let's say if you try to rename your controller name from “EmployeeController” to “EHomeController”, then in such cases your user's bookmarks will not work and it could have a bad impact on the user's opinion about the functionality of the website. So for reducing such types of issues we can make an entry in the route mapping. The following could be the entry.

1.   For demonstrating this we'll rename our “EmployeeController” to “EHomeController”

2.   Add the following entry in the RouteConfig.cs file as the first entry in the RouteConfig.cs file. 

routes.MapRoute(
                 name: "OldURL",
                 url: "Employee/{action}/{id}",
                 defaults: new { controller = "EHome", action = "Index", id = UrlParameter.Optional }
             );

 NOTE:In the preceding entry, in the URL we've statically defined the controller name as “Employee” and dynamically specified the Controller segment value as “EHome” (the value that should be treated at runtime for EmployeeController) that is basically the renewed name of our Controller. Just try the application by entering /Employee/Index in the browser's URL, you'll get the result without any error, even though you've changed the Controller name from “EmployeeController” to “EHomeController” in your code.

Introduction of Routing in MVC

When change url Employee/Index then return message of EHomeController class because we have map this url in RouteConfig.cs file

Introduction of Routing in MVC

 

In my next post I’ll explain about Chang Url with help URL Routing.


I am a content writter !

Leave Comment

Comments

Liked By