ASP.NET MVC > Route

Define new route in ASP.NET MVC in ASP.NET MVC

How to define a new route in ASP.NET MVC?


To define a new route, go to ~/App_Start/RouteConfig.cs file and write  new route just after routes.IgnoreRoute statement.

ROUTECONFIG.CS CODE

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "MyCustomRoute",
                url: "MyEmployees/{action}/{id}",
                defaults: new { controller = "PersonalDetail", action = "Create", id
= UrlParameter.Optional }
            );

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

Notice the above code snippet (highlighted), we have defined MyCustomRoute just after routes.IgnoreRoutes and the default route “Default”. This is because the default route defined is more of a generic nature that takes care of any three segments passed in the url for Controller, Action and Id (optional). So if we define our custom route after the default routes, the default routes will execute and our custom routes will never executes. So while defining new routes, we need to define from specific to generic routes.

In our custom route, we have instructed ASP.NET MVC framework that if any url request is starting with MyEmployees, route it through MyCustomRoute routes rules.

 Views: 19085 | Post Order: 67



Write for us






Hosting Recommendations