1

I'm developing an ecommerce application, using ASP.net MVC 3

Having some trouble figuring out the best way to map "categories"

For each category, I have a root page - that will display some offers, info, etc.. (these are examples)

  • /books
  • /clothes
  • /electronics

Currently, I have a books controller, and a sports controller, and an electronics controller Index of each returns the appropriate view...

This seems a little "clunky" as if a new category is added, we have to create a controller for it..

In the product database, I have categories "flattened" in a hierarchy. So, a book on computing might have:

  • /books/
  • /books/non-fiction/
  • /books/non-fiction/computing

I also have a "search" controller This handles product searching (search/?q=some query) Also, can do search/?q=*&category=/books/non-fiction/computing - this would show all products with /books/non-fiction/computing listed as a category.

So... I think what I'm trying to do... is route the "root" category to show the default view for that category. If there is anything after that, should be treated as a category search...

Is there a way of doing this?

Alex
  • 37,502
  • 51
  • 204
  • 332

1 Answers1

1

I think the best solution would be to just have a product controller where the index action takes an optional parameter. If parameter is empty or null then just return the default list of products you'd like to display, otherwise, filter the products based on the category that is provided in the string.

So for example this would be the URL's:

/products/books 
/products/clothes 
/products/electronics
/products/whatever

Or you could just add routes for each category if you don't like the URL that is formed to send it to whatever controller/action you like. Its honestly personal preference and whatever you like best.

For example:

context.MapRoute(
          "books_route",
          "products/books/{type}",
          new { controller = "product", action = "books", type= UrlParameter.Optional }
      );

or 


   context.MapRoute(
          "books_route",
          "books/{type}",
          new { controller = "product", action = "books", type= UrlParameter.Optional }
      );
  • Thanks - That still means I need to create a route per category..? For example, if we added a "toys" category, I'd have to modify my global.asax accordingly? – Alex Oct 04 '11 at 16:30
  • Yes, but you can also all multiple parameters to your route so you can pass in {category} and {type} in one route. As long as your action filters accordingly you shouldn't have create new routes for each product if you don't want to. –  Oct 04 '11 at 16:52