Reputation: 337
I have some problems with my URL look while going through categories.
Basically, this is some kind of catering application where user selects Town
(top category), then selects Restaurant
for that town
, and inside restaurant
he can see food
.
I have TownViewController
, RestaurantViewController
, FoodViewController
and main action that handles representation of Town
, Restaurant
, Food
is View
(so in every controller).
To see all towns I have www.catering.com/Town
and thats fine (though it would be better if its /Towns without renaming controller to Towns nor hardcoding new route - if possible)
To see all restaurants for selected town (in this case ID=1) I have www.catering.com/Restaurant/View/1
. Now here is problem. This should actually be route when restaurant is selected and foods are represented, and for restaurant representation should be www.catering.com/Town/View/1
. So actually always super category should be in URL.
Because at the end I have www.catering.com/Food/View/1
and that makes no sense since I'm viewing restaurant not Food with id=1.
Is there some way this can be fixed except classical hardcoding of routes? I managed to work it out with some hardcoded routes but my client said its not good way since it can get pretty messy in bigger projects.
I've done like this:
routes.MapRoute(
"Restaurant",
"Town/View/{id}",
new { controller = "Restaurant", action = "View", id = UrlParameter.Optional }
);
routes.MapRoute(
"Food",
"Restaurant/View/{id}",
new { controller = "Food", action = "View", id = UrlParameter.Optional }
);
Upvotes: 0
Views: 340
Reputation: 239290
I would suggest attribute routing. If this is an MVC 5 project, you just need to go into RouteConfig.cs
and in your RegisterRoutes
method, uncomment/add the line:
routes.MapMvcAttributeRoutes();
Then, you can use the Route
attribute and RoutePrefix
attribute to specify the exact URL you want. For example:
[RoutePrefix("Town/View/{townId}")]
public class RestaurantController
{
[Route("")]
public ActionResult Index(int townId)
{
...
}
}
If you aren't running MVC 5, you can add the nuget package, AttributeRouting. The syntax is similar, but slightly different. Instead of using Route
, you use one a several attributes based on the HTTP method:
[RoutePrefix("Town/View/{townId}")]
public class RestaurantController
{
[GET("")]
public ActionResult Index(int townId)
{
...
}
}
Upvotes: 2
Reputation: 2562
Have you tried using MVC Areas to further segment your site? Here is a link explaining the usage: Walkthrough: Organizing an ASP.NET MVC Application using Areas
Upvotes: 1