What is Routing


Routing is the way to create user friendly and descriptive url. In mvc when you add project we are able to see RouteConfig.cs file in our app_start folder.
In this file you can see default root has been mapped.

RouteConfig.cs

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

  
  
Routes are basically the RouteCollection which can have more than one route. Name is the route name which is always unique. Url is the pattern in which application will be opened. According to this pattern it will take controller name and action name. Id is the optional parameter.
Now add controller and create two actions inside it. And create views for these actions.
  
 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }
    }

}
 
  
Now I want to add one more route for login.
  
 routes.MapRoute(
               name: "Login",
               url: "login",
               defaults: new { controller = "Home", action = "Login" }
           );

    
  
Now execute this code
If we pass controller/action then it will use the default route.

But if I simply write login in url it will simply execute the login route which I have added.

In this way we can add more than one route for our application. Always remember that if we have to add more than one route then default route will always be kept on last otherwise it will always execute the default.
Final RouteConfig.cs after adding multiple route
  
  public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               name: "Login",
               url: "login",
               defaults: new { controller = "Home", action = "Login" }
           );

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

No comments:

Post a Comment