How to define a route in ASP.NET MVC?

You can define a route in ASP.NET MVC as given below:

public static void RegisterRoutes(RouteCollection routes) {
	routes.MapRoute("Default", // Route name
	"{controller}/{action}/{id}", // Route Pattern
	new {
		controller = "Home", action = "Index", id = UrlParameter.Optional
	} // Default values for above defined parameters
	);
}
protected void Application_Start() {
	RegisterRoutes(RouteTable.Routes); //TODO:
}

Always remember route name should be unique across the entire application. Route name can’t be duplicate.
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. Here is a list of URLs that match and don’t match this route pattern.

Request URL Parameters
http://example.com/ controller=Home, action=Index, id=none, Since default value of controller and action are Home and Index respectively.
http://example.com/Admin controller=Admin, action=Index, id=none, Since default value of action is Index
http://example.com/Admin/Product controller=Admin, action=Product, id=none
http://example.com/Admin/Product/1 controller=Admin, action=Product, id=1
http://example.com/Admin/Product/SubAdmin/1 No Match Found
http://example.com/Admin/Product/SubAdmin/Add/1 No Match Found

Note: Always put more specific route on the top order while defining the routes, since routing system check the incoming URL pattern form the top and as it get the matched route it will consider that. It will not checked further routes after matching pattern.

Tagged , . Bookmark the permalink.

Leave a Reply