Dkong
Dkong

Reputation: 2788

mvc routing examples for categories and sub-categories

i have a static website (no database) and am having difficulty understanding how to setup routes for sub-categories. for example, i can do the following where the category is the controller and the make is the action:

but when i add another level i don't know how to setup the route

Upvotes: 0

Views: 3986

Answers (2)

Mikael Östberg
Mikael Östberg

Reputation: 17156

You should be ok with a route looking like this:

routes.MapRoute(
   "CarsRoute",
   "cars/{make}/{model}",
   new { 
      controller = "Cars", 
      action = "Display", 
      make = UrlParameter.Optional, 
      model = UrlParameter.Optional 
   });

This would map to an action method with the signature:

public ActionResult Display(string make, string model)

Where both make and model can be null. You can then perform your actions.

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532475

I'd probably go with year/make/model

routes.MapRoute(
   "Default",
   "{controller}/{year}/{make}/{model}"
   new
   {
       controller = "car", 
       action = "search",
       year = DateTime.Today.Year,
       model = "all",
       make = Url.OptionalParameter
   }
);

(you might want a constraint on the year to force it to be a reasonable value?)

with a controller like

public class CarController 
{

    public ActionResult Search( int year, string make, string model )
    {
         // handle model "all" and empty "make" specially
    }
}

Upvotes: 1

Related Questions