views:

1291

answers:

3

I'm thinking of learning the ASP.NET MVC framework for an upcoming project. Can I use the advanced routing to create long URLs based on the sitemap hiearachy?

Example navigation path:
Home > Shop > Products > Household > Kitchen > Cookware > Cooksets > Nonstick

Typical (I think) MVC URL:
http://example.com/products/category/NonstickCooksets

Desired URL:
http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick

Can I do this?

+2  A: 

The MVC routing lets you define pretty much any structure you want, you just need to define what each of the pieces mean semantically. You can have bits that are "hard-coded", like "shop/products", and then define the rest as variable, "{category}/{subcategory}/{speciality}", etc.

You can also define several routes that all map to the same end point if you like. Basically, when a URL comes into your MVC app, it goes through the routing table until it finds a pattern that matches, fills in the variables and passes the request off to the appropriate controller for processing.

While the default route is a simple Controller, Action, Id kind of setup, that's certainly not the extent of what you can do.

J Wynia
A: 

Would all of "household/kitchen/cookware/cooksets/nonstick" (with the slashes) be a valid single id for a route such as "[controller]/[action]/[id]"?

Or would I have to create several routes? One for each possible depth?
Url = "[controller]/[action]/[category1]"
Url = "[controller]/[action]/[category1]/[category2]"
Url = "[controller]/[action]/[category1]/[category2]/[category3]"
Url = "[controller]/[action]/[category1]/[category2]/[category3]/[category4]"

Or would I have to programmatically generate the routing table based on the sitemap? One route per page.

Zack Peterson
Andrei Rinea: "{controller}/{action}/{*categoryPath}" will do the trick the important part is * that ensures wildcard mapping to N-level categories, but your controller needs to parse the categories manually
Claus Thomsen
+7  A: 

Zack, if I understand right you want unlimited depth of the subcategories. No biggie, since MVC Preview 3 (I think 3 or 4) this has been solved.

Just define a route like

"{controller}/{action}/{*categoryPath}"

for an url such as :

http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick

you should have a ShopController with a Products action :

public class ShopController : Controller
{
...
    public ActionResult Products(string categoryPath)
    {
        // the categoryPath value would be
        // "household/kitchen/cookware/cooksets/nonstick". Process it (for ex. split it)
        // and then decide what you do..
        return View();
    }
Andrei Rinea