routing in mvc 4

sam
sam
378 Points
48 Posts

Hi,

Please, any one explain the routing in mvc. How can I use it.

Views: 10783
Total Answered: 2
Total Marked As Answer: 0
Posted On: 20-Aug-2015 21:57

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4916 Points
27 Posts
         

Hi Sam,

ASP.NET MVC routing is a pattern matching engine that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match.

When the MVC application launches the Application_Start() event handler of the global.asax execute that call the RegisterRoutes() method from RouteConfig class under App_Start directory (App_Start/RouteConfig.cs). The RegisterRoutes() route has a parameter that is a collection of routes called the RouteCollection that contains all the registered routes in the application. The following represents the default method that adds routes to the route table.

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //Ignore routes that end with axd extension
routes.MapRoute(name:"Default",
url:"{controller}/{action}/{id}",
defaults:new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
  • Route Name:A route name may be used as a specific reference to a given route.
  • URL Pattern: A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL that are delimited by the slash (/) character.
  • Defaults:When you define a route, you can assign a default value for a parameter. The defaults is an object that contains default route values.
  • Constraints: A set of constraints to apply against the URL pattern to more narrowly define the URL that it matches.

 

Posted On: 27-Aug-2015 04:29
Smith
Smith
2890 Points
78 Posts
         

Hi sam,

You can create own routing by using MapRoute above of the default routing as:

 

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //Ignore routes that end with axd extension
routes.MapRoute(name:"AboutUs",
url:"about_us",
defaults:new { controller = "Account", action = "AboutUs" }
);
routes.MapRoute(name:"Default",
url:"{controller}/{action}/{id}",
defaults:new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

In the above I have added a AboutUs routing with controller 'Account' and Action 'AboutUs'

You can request for about us as

[domain]/aboutus
Posted On: 21-Dec-2015 07:05
 Log In to Chat