Routing in MVC:-

In traditional web frameworks like Classic ASP, JSP, PHP and ASP.Net, Url represents the physical file. Where as in MVC framework, URL is mapped to the method call in the class, rather than file.

MVC – Controller is the class that interacts between the user input and other components.

Action – are the methods in the controller class serves the response

When you type the URL in the browser and click, corresponding controller action method is called? How URL is mapped to the right controller? Who is doing this job?

Answer: Routing engine

Routing server two main purpose in MVC framework

  1. Routing server two main purpose in MVC framework
  2. Constructs outgoing URLs that correspond to controller actions

You can check the Routing happens in the “App_Start\RouteConfig.cs”

       
        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 }
            );
        }

    
    

You can see in the above code, Routing URL is mapped with controller action in the following format “[Controller Name]/ [Action method name] / [Method parameter]”

       
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional
    
    

This section in the MapRoute provides a default value for the {Controller}, {action} and {id} parameter. If you are setting default value for the {action} parameter, then it is mandatory to set the default value for the {id} parameter.

It is not necessary that you have to specify the url as above mention pattern. You can define your own patterns

Route URL Pattern URL that match Comments
{controller}/{action}/{id}", /Home/About/5 Id is the parameter to the action method e.g: public ActionResult About(int id) {}
Mysite/{action}-{format}", /Mysite/display-xml Here “MySite” is constant and it always comes before action method name
{report}/{year}/{month}/{day} /sales/2012/5/25 Here controller action methods are identified using Route constrain