views:

141

answers:

1

Being rather new to ASP.MVC I'm looking for a solution to the following routing problem.

I want these Url's to lead to the shown pages:

/Member/123/A+Strange+Username -> page with members details
/Member/123 -> as above
/Member/Connections/123 -> page with list of members connections
/Member/Connections/123/A+Strange+Username -> as above
/Member/Comments/123 -> page with list of members comments
/Member/Comments/123/A+Strange+Username -> as above

The username should be ignored but will be appended to links to help search engines.

I have tried with the following routes:

routes.MapRoute("MemberPage", "Member/{id}/{*name}", new { controller = "Member", action = "Details", id = "" });
routes.MapRoute("MemberAction", "Member/{action}/{id}/{*name}", new { controller = "Member", action = "Details", id = "" });

But it seems it always defaults to the first route, and then gets an error since "Connections" or "Comments" is invalid id's for the Details controller.

Is there a way to switch route depending on the type of the id-value, or another way to solve this?

+5  A: 

It might help if you add a route constraint to the {id} both routes.

routes.MapRoute("MemberPage", "Member/{id}/{*name}",
      new { controller = "Member", action = "Details", id = "" },
      new { id=@"\d+" });
routes.MapRoute("MemberAction", "Member/{action}/{id}/{*name}",
      new { controller = "Member", action = "Details", id = "" },
      new { id=@"\d+" });

This way, it won't try to map "Comments" to {id} in the first route and will fall through to the second one which should work fine with that URL.

dhulk
Works like charm! Thanks!
hbruce
Thank you for the answer
Barbaros Alp