Domanda

I have some problems managing good looking URL for my site.

I have 3 models: Town, Restaurant, Food.

TownController is using TownService and Index shows all Towns (other methods are Edit, Create, Delete)

Similar is with RestaurantController - using RestaurantService and Index shows all Restaurants in chosen Town)

FoodController - using FoodService and Index shows all Foods in chosen Restaurant

URLs:

/Town - shows all towns

/Restaurant/Index/1 - shows all restaurants in Town with ID = 1

/Food/Index/1 - shows all foods in Restaurant with ID = 1

Only /Town is fine URL, rest are not good. Second should be more like /Town/1 but since RestaurantController is showing all restaurants in Town it must be written /Restaurant/Index/1.

Is there way to change that construction? Also note that client insists on not using custom routes/attribute routing.

Best SEO at end would be /Town/TownName/RestaurantID (or even restaurantName) but thats not that important if you could help me with previous request.

Thanks.

È stato utile?

Soluzione

You need to modify and add some custom routes to RouteConfig.cs in your App_Start folder. You should have the following default route in the RegisterRoutes method

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

This route means that if you pass it nothing for the controller, the action or the id it will go to /Home/Index/, if you pass it a controller it will got to /Town/Index. If you register the following route BEFORE the default route (they get tried in order, so the default route should always be last)

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

this will capture any url that has '/Town/' and an integer while still letting '/Town/' by itself go to the Town controller.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top