views:

203

answers:

1

I would like to set up a route for a controller that has the normal CRUD operations, but would like the Details action not show 'Details' in the URL. Stackoverflow seems to have this type of routing configured:

http://stackoverflow.com/questions/999999/
http://stackoverflow.com/questions/ask

Using this analogy, my routes currently look like:

http://stackoverflow.com/questions/Details/999999/

By adding the following route I was able to get Details removed:

routes.MapRoute("Q1", "questions/{id}", 
    new { controller = "Questions", action = "Details" });

However, pulling up other actions on the controller (e.g. /questions/new for this example) is complaining that the id cannot be parsed.

Is there a way to set up the routes so that I don't have to manually enter all the other actions (MapRoute "items/create", "items/delete", etc.) manually into the Global.asax.cs? I essentially would like to have a second route like:

routes.MapRoute("Q2", "questions/{action}", 
    new { controller = "Questions", action = "Index" });

... and have the routing engine use route Q1 if {id} matches an integer, and {action} if it is a string. Is this possible?

+5  A: 

If you put a route constraint on the first one so that the id field can only be an integer then I believe any other actions will fall through to the default.

routes.MapRoute("Q1", 
   "questions/{id}", 
   new {controller = "Questions", action = "Details"},
   new { id=@"\d" });

Anything else should be handled by the default route. So "questions/3553" would hit this one but "questions/ask" would not match. You'll probably want to put the more specific route first in your Global.asax.cs file.

dhulk
This worked perfectly. Note, however, that the constraint needs to read as @"\d+".
Jason
Thanks for the clarification, I normally use a length limiter after the expression (i.e. @"\d{2}") so I wasn't exactly sure what to put to simply have an integer.
dhulk