Introduction to Routing in MVC

In traditional web applications, we create a web form (or pages) which maps to the physical file on the disk.  We, then use the URL like www.eCommerceSite.com/Items.aspx, where  Items.aspx is the resource which exists on the disk.  But in an MVC Application we create Controller, Views and modelsASP.NET MVC uses an ASP.NET routing to map URL to the Controller actions.  In this article we will look at  how Routing in MVC works.

Open the MVCHelloworld, which we created in the last tutorial. If you missed those tutorials here is the link.

Create ASP.NET MVC Application
Create ASP.NET MVC Application – Add View
Create ASP.NET MVC Application – Add Models
Create ASP.NET MVC Application -Add CRUD Function

Routing in MVC

Understanding ROUTING IN MVC
Understanding ROUTING IN MVC

How it works

When you run any application built on ASP.NET MVC  the URL you type in the address bar of the browser is sent to the web server.  The Web server redirects the request to MVC Application.

  1. The URL of the web application typed in the browser
  2. The URL is sent to the Server by the browser
  3. The Server passes the URL to the MVC Application
  4. MVC Application takes a look at the URL and decides which controller action to use and invokes the controller action
  5. The Output of the controller action is returned to the browser.
  6. Waits for the further user interaction, which will start a fresh cycle.

In MVC step 4 is known as routing

What is a Routing

Routing is a process by which MVC applications decide, which controller actions to be used to handle the user request.

Run the MVCHelloWorld Application and you will see that the Hello World is displayed in the web browser.  This is because the routing module passed the control to HomeController which in turn executes the Index Action.

How does Application determine which controller to use?.  Well, it reads it from the collection of the route. 

What is a route

The Route is similar to a roadmap. We use a roadmap to go to our destination. Similarly, the MVC Application uses the route to go to the controller action.

Where do the Routes are Stored ?

All the application Routes of are stored in RouteTable. The RouteTable is a global variable which is created when our MVC Application is started. This is shared across all the users using the application.

The Routetable contains property by the name Routes (Routetable.Routes). It contains the collection of all the routes. We can add our own routes to this collection.

How and when to add Routes

Naturally the routes must be added to the Routetable.Routes collection at the start of the application. So that users who are connecting to the application by typing URL in their web browser are taken to the correct controller action.

The best place is to add route is in Application_Start  method

 Application_Start

MVC Routing Basics Global.asax
MVC Routing Basics Global.asax


Application_Start
is the first method that executes in an ASP.NET Web application. When the user initiates a first request to an ASP.NET web application, the application calls the Application_Start method. This method is called only once during the life cycle of the application.

This method is found in global.asax , which is located in root folder of the project.

You can see that the Application_start calls the RouteConfig.RegisterRoutes method. It passes the RouteTable.Routes collection to the RouteConfig.RegisterRoutes.  As we explained in the previous section RouteTable.Routes is where all the routes of the application are added.

RouteConfig.RegisterRoutes

MVC Routing Basics RouteConfig

MVC Routing Basics RouteConfig

RouteConfig.RegisterRoutes is found in RouteConfig.cs , which is located in the App_start folder

RouteConfig.RegisterRoutes method is responsible for registering the routés.  The RegisterRoutes function is as below

As we can see from above,  routes collection calls the  routes.MapRoute  function to add routes to the routes collection.

The first parameter is the name of the route. Name of the route in the above example is the default.

The second parameter is the url Pattern of the route.  In the above code it is specified as “{controller}/{action}/{id}”

When a user request is received by the Application, it tries to parse the URL and uses the above pattern and maps the url to a controller action. Url Pattern is explained in the section below.

The third parameter is defaults.  When nothing is specified in the url the controller and action specified in the url are executed

URL Pattern

The url pattern contains URL parameters. Each URL parameters is enclosed in a curly brackets {}. Forward slash / separates the URL parameters from each other

MVC MapRoute
MVC MapRoute

In the above image, the sample route contains three URL parameters i.e. controller, action and id.

URL pattern-matching

MVC uses the pattern-matching rule to process the incoming requests. For example Product/List/Computers will match the URL Pattern with three URL Parameters as shown in the image below

MVC URL Pattern Matching
MVC URL Pattern Matching

The above URL will execute the List action method in the Product Controller passing it Computers as the parameter. It is similar to the executing the  Product. List (“Computers”) 

Back to MVCHelloWorld

Now lets go back to our project. Run the project. The Browser will display “Hello world”

Since we have not specified anything in the url  the routing module used the defaults which is

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

Now type /home at the address bar. The Browse will display “Hello world”

The controller Home exists and since nothing specified in the action defaults action index is executed

You can try the following url

UrlResult
/Hello World
/HomeHello World
/home/IndexHello world
/TestError Resource not found.

There is no controller by the name Test. Hence returns an error
/Home/TestError Resource not found.

Home controller exists, but Test action dose doesn't exist, hence returns an error

Now go ahead and create a method Test  in HomeController class

Now try the following

localhost:6020/Home/Test                                         This is Test

Now we have to test methods in HomeController. Hence the output of the test method is displayed in the web browser.

Conclusion

In this tutorial, we tried to explain how Routing works in MV, Application.  MVC Routing module makes an excellent work of decoupling the URL from the physical file. It Provides a way to map URLs without extensions to controller actions.

Links to How to create ASP.NET MVC Application

Create ASP.NET MVC Application
Create ASP.NET MVC Application – Add View
Create ASP.NET MVC Application – Add Models
Create ASP.NET MVC Application -Add CRUD Function

Download

Source Code

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top