Routing in Asp.Net MVC with example

                       Routing in Asp.Net MVC with example  


        Routing is defined in the RegisterRoutes method inside the RouteConfig class.
        this RouteConfig class resides in App_Start Folder.
      
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

           
        }

        Routing is a pattern matching system . when any user request from the browser at runtime 
        Routing engine use routing table for matching user request URL pattern against the URL 
        a pattern that is defined in the Route table.  You can register one or more URL
        patterns in the route table but name is require different for each route. 

        you can see the above route is configured using the MapRoute() method of RouteCollection,
        where name is the default , URL is {controller}/{action}/{id} and default specify controller ,
        action and id which is optional.

        every MVC application has one route which is the default route.

        
       

                             How Routing Work in MVC

        when the application run first application_start event from global.asax is fire. 
             inside the application_start route is registered. 

              RouteConfig.RegisterRoutes(RouteTable.Routes);
          
            so when the application run it initialize route. 

          when a user hit any URL from a browser at runtime route engine check incoming URL pattern              and register route pattern. if patten is found then it go to controller and perform an action and                   return view. if URL pattern not found it give 404 not found error.
     
          let understand with an example 

          http://localhost:8989/Account/Index 
      
          in the above Account is a controller and Index is an action method. when a user hit above URL 
          in the browser. this URL pattern checks with register route pattern at runtime by route engine. 
          if the URL pattern is found. it goes to Account controller  and checks Index method and go
          index method and execute a method and return view. if the URL pattern not found it give you
          404 error.





  

Comments

Popular posts from this blog

How To Create an MVC application in Visual Studio 2019

ActionResult Return Type in MVC

Explain terms of MVC ?