Search code examples
asp.net-mvcroutesmarketplace

How to set {city} in all the routes MVC 5


I am developing a marketplace application which is supposed to have different products and vendors which are mapped to different cities. The idea is that I need to store the CurrentCity in context so that I can use it to construct urls, filter data, fetch delivery areas etc. e.g.

www.mywebsite.com/cityA/listings
www.mywebsite.com/cityB/listings

www.mywebsite.com/cityA/cart
www.mywebsite.com/cityB/cart

Something like the MoonPig website (https://www.moonpig.com/uk/Gift/Flowers/)

Currently, I am passing the city as a parameter in almost all the controller methods and also storing it in a cookie.

Alternatively, I am also thinking of creating a BaseController and possibly inject it in the OnActionExecuting(ActionExecutingContext context).

But the problem with the first approach is that all the Action methods need to have "city" as a parameter and I need to have it in context for doing something like

@Url.Action("Index", "Listings", new {city = cityName})

If I use the second approach, then I don't think I'll get the urls which have city in them.

I am ideally looking for a solution with which I can inject a city parameter as Base route / segment in the MVC RouteDictionary so that all the Urls are generated accordingly (with @url helper).

Is this possible or is there a better way to tackle this problem? Would really appreciate if someone can show me a direction.


Solution

  • But the problem with the first approach is that all the Action methods need to have "city" as a parameter

    This assumption is incorrect, since MVC automatically passes values from the current context when generating URLs, so there is no need to explicitly pass city as long as it is configured in the route and present in the URL. See this answer for how you can utilize this behavior for localization, which is similar to what you are doing.