Click here to Skip to main content
15,885,916 members
Articles / All Topics

Routing in MVC

Rate me:
Please Sign up or sign in to vote.
4.83/5 (5 votes)
31 Dec 2014CPOL5 min read 13.8K   11   3
As we have seen in the last article ,Controller in MVC application is the component which takes care of the user input ,as well as defines the application logic.It performs operations on the model...The post Routing in MVC appeared first on codecompiled.com.

As we have seen in the last article ,Controller in MVC application is the component which takes care of the user input ,as well as defines the application logic.It performs operations on the model and then selects the view to render.

Routing has it’s own specific responsibility.It acts as the interface between the clients request and the Controller which serves the request.As the client does not request any specific page,as in the case of web form pages ,so the responsibility of Routing component is more important in MVC.Without the Routing component there is no way that the request can be mapped to a particular controller.A URL such as http://www.ecommerce.com/product/1 have no meaning by itself ,it is only because of the routing component that our application is able to handle the request.

Routing subsystem contains a collection of routes.Each route contains the information on what all requests the route will match and which controller and action method will handle the request.

1.What requests the route will match is identified by the url pattern defined by the route.

2.Which controller and action method will handle the request is identified by the {action} and {controller} parameters declared by the route.

We will look at the default route created when we create a new MVC application and see how the route handles the two points mentioned above.

Create a MVC project and open the RouteConfig.cs file in the App_Start folder.

routing in mvc

It contains a RegisterRoutes method defined as

public class RouteConfig
{
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 }
);
}
}

RegisterRoutes method is called from the Application_Start method when the application starts

routing in mvc

As we can see above a routecollection object ,routes, is being passed to the RegisterRoutes method.This collection object contains all the routes defined by our application.
RouteCollection class defines a method called MapRoute which is used to add new routes to the route collection.

Before moving ahead lets see what is a route.Routes are what we define to handle the requests that our application receives.Route has few important characteristics

Route is identified by a name
Route has a URL pattern which is used to match the URL’s that the route will handle.
URL pattern can consist of route parameters which are just variables which are populated by values from the URL.

Route can define default values for the route parameters.

If we take the example of the default route ,there is a named parameter url being passed to the MapRoute method.It has the value “{controller}/{action}/{id}”.This pattern has three segments.

routing in mvc
We can identify each segment by the “/” character .The forward slash (“/”) character separates each segment in the URL pattern.The segments in this pattern are all route parameters.The route parameters are just placeholders and are identified by curly braces {} .Each segment can contain literal values or the placeholders or a combination of both.

So the following url pattern is perfectly valid.

url:"{segment1}/{segment1}/{segment3}"

The important point is that the above url pattern will match any url having three segments.This answers the first point that we discussed above What requests the route will match

So our new url pattern will match url’s such as

http://xx/yy/zz

Though the pattern we have defined above is perfectly valid but it is not of any use as it will not forward the request to any controller class and action method.If we look at the default route pattern it is defined as

"{controller}/{action}/{id}"

The {controller} and {action} placeholders have spacial meaning in MVC as they represent the controller and the action method which will handle the request.So if we make a request using the url http://Home/Index then the Index method in the Home controller is invoked.The first segment corresponds to the controller name and the second segment corresponds to the action name which will handle the request.

So now we know that Who will handle the request is identified by the {action} and {Controller} route parameters.

Though we have declared the inbuilt {action} and {controller} parameters above but we can declare our own parameters in the route pattern.We can pass values to action method using these.So we can declare a {name} route parameter like

"{controller}/{action}/{name}"

The value of the name parameter will be fetched from the url and will be used to populate the action method parameter name.

routing in mvc

We have seen what is url pattern in a route and how the route identifies the action method and the controller which will handle the request.There are few other things that should be considered when declaring routes

Default parameter values We can define the default values for the route parameters defaults parameter.If the url does not contain a segment specified in the url method argument then the value we have supplied to the defaults argument will be used for the {action} and {controller} parameters.

As we have seen earlier our default route is defined as

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

The defaults argument values will be used used for both the controller and the action method if we don’t supply values for these.If we look into the project properties the project Url is defined as below.So if we run the application the url requested is the application root url or “/”.The reason that the Index action in the Home controller is executed is because of the defaults argument which sets the value of Controller as Home and action as Index.

routing in mvc

Order matters while adding the routes to the route collection The routes which we add to the route collection are matched with an incoming request in the order in which we add them.So the incoming URL will match the first route we added to the collection and if the match is found then it will not try to match the url with the url patterns of the other routes.So if we define a generic url pattern which would be matched with any url at the beginning of the route collection then our remaining routes will not be matched to the incoming url.

So as we have seen routing is an important component in mvc application which maps the requests to the action methods which handles the request.

The post Routing in MVC appeared first on codecompiled.com.

License

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


Written By
United States United States
I have a keen interest in technology and software development.I have worked in C#,ASP.NET WebForms,MVC,HTML5 and SQL Server.I try to keep myself updated and learn and implement new technologies.
Please vote if you like my article ,also I would appreciate your suggestions.For more please visit Code Compiled

Comments and Discussions

 
GeneralURL structure Pin
Bazmech2-Jan-15 13:55
Bazmech2-Jan-15 13:55 
Questionlink? Pin
ccrngd131-Dec-14 3:19
professionalccrngd131-Dec-14 3:19 
AnswerRe: link? Pin
ashish__shukla31-Dec-14 18:28
ashish__shukla31-Dec-14 18:28 

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

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