views:

50

answers:

1

I have a small site I am working on where I need to have 3 different routes such as:

  1. .com/id/foo

2 .com/id/foo/bar

3 .com/id/foo/bar/user

So number 1 would be for the id of foo. Route 2 would be the id of bar. Finally route 3 would be the id of the user.

How would I set the routes up to do this?

+1  A: 

If all of those map to a single controller and action, you can accomplish it like this:

  routes.MapRoute("Default",
                "{id}/{foo}/{bar}/{user}",
                new { controller = "Home", action = "Index", 
                      foo = String.Empty, 
                      bar = String.Empty, 
                      user = String.Empty }); 

And your Index action would look like:

public ActionResult Index(string id, string foo, string bar, string user) {}

If your intent is that each of those is a separate action, then consider that routes are matched in the order that they are added to the routing table. Therefore, always add the routes in order of most specific to broadest, and you'll be fine. So:

  routes.MapRoute("Default",
                "{id}/{foo}/{bar}/{user}",
                new { controller = "Home", action = "FooBarUser" }); 

  routes.MapRoute("Default",
                "{id}/{foo}/{bar}/",
                new { controller = "Home", action = "FooBar" }); 

  routes.MapRoute("Default",
                "{id}/{foo}/",
                new { controller = "Home", action = "Foo" }); 
womp
Thanks, your 2nd method was exactly what I was looking for. I was a little rusty with the route syntax.
dean nolan