Search code examples
asp.net-mvcasp.net-mvc-routing

How to change url as parameter will look like controller name in mvc


Currently the url in the address bar displays as

example.com/?City=Canada&para1=&para2=&....

Is it at all possible to make the url be:

example.com/Canada/?para1=&para2=&....

Following route is being used:

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

But is it possible to do this without creating "Canada" Controller or Action Method? It should also do the same thing as the first url does.


Solution

  • Just place something like the following before your current default route.

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

    Essentially, this just says that the first path in the route constitutes a "city" param. So, in a route like /Canada/, city would be "Canada", and controller/action would be the defaults of "Home" and "Index" (since they weren't provided in the route).

    Note: You are aware Canada is not a city right?