How Routing works in MVC Application

In Brief:
In this article i will explain how the routing is done in MVC Application. In the previous article  we have seen how the input request is get processed .
Let us progress with the same code from request processing article.

In Detail:
if we run this code 
URL goes like this
This URL not even contain the controller name or action method, but on execution it correctly mapped to controller class “Home” and action method “Index”. Let us look at in steps to know how it is done.

Open theGlobal.asax it contains the event handler method called Application_Start. This event fires on the application start. This contain the call to RegisterRoutes() method of RouteConfig class. 
If we made “Go to definition” on RegisterRoutes() it redirects to RouteConfig class defined in the App_Start folder of the project.

How Routing works in MVC Application

How Routing works in MVC Application

Here we can see RegisterRoutes() method. Let us first focus on the second part where routes is initialized  the name,url and default parameter. This Route is named as “Default”.
Here the application path format is  Controller/Action/Index. In the defaults, controller and action is initialized with “Home” and “Index ” respectively.  
If we run the application now without passing the particular controller and index method  name by default it will take /Home/Index as it is mentioned in the RouteConfig.

Second parameter for defaults  i.e. “id” is optional,To make use of this id let us change our code as follows
public string Index(string id)
return “Id= ”+id;

after run change the url as :
localhost:1051/home/index /5

we can also pass the key,value as parameter
public string Index(string id,string name)
return “Id= ”+id + “name = ”+name;

after run change,append the id parameter as follows
localhost:1051/home/index /5?name=suchith

How Routing works in MVC Application
Any Query string or post parameter with named “name” is always passed to index action method
ASP.Net MVC automatically pass the any query string or form post parameter named “name” to action index method when it is get invoked.

Let us now consider the first line in the RegisterRoutes method which is, routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
it says that ignore the file with extension .axd.  On run of any MVC application it might generate the .axd files(e.g. trace.axd) and it contains the path information.Here we don’t want to add that path information contained in that file.Because we have explicitly mentioned the Default route in the bellow line and we need that is is to be taken by the application.

Final Touch: On start of any MVC application,Controller searches for the default route information mention in the route config class. Routing is done according to that for the first time.
keep visiting for the next article in mvc getting started.

Please write back for any suggestion/Clarification.

No comments:

Post a Comment