views:

29

answers:

1

Hi,

I've got two (so far) different types of routes in my ASP.NET MVC app, one is: {controller}/{action}/{id} and the other {controller}/{action}/{title}

Currently I need to define the routes like this:

        routes.MapRoute (
            "Default_Title_Slug",                                       // Route name
            "product/details/{title}",                          // URL with parameters
            new { controller = "product", action = "details", title = "" }      // Parameter defaults
        );

        routes.MapRoute (
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "site", action = "index", id = "" }  // Parameter defaults
        );

Notice that the first one I've had to tie down to the product controller, this seems to be the only way I can get it work...otherwise the other routes end up looking like this:

/controller/action?id=number

Now I need to add another MapRoute call targeting another controller with the {title} segment...I don't want to create a new route for each specific entry I come up with in the future...is there a generic route I can create to map the /controller/action/title that'll play nicely with the /controller/action/id route?

Thanks,
Kieron

+4  A: 

You can do that with a route-constraint, such as regex - a very similar example is here. Something like:

routes.MapRoute (
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "site", action = "index", id = "" },
    new { id = @"\d+" }
);
routes.MapRoute (
    "Default_Title_Slug",
    "{controller}/{action}/{title}",
    new { controller = "product", action = "details", title = "" }
);
Marc Gravell
Perfect, thanks!
Kieron
And just to be clear, the Default_Title_Slug can now have it's url changed to {controller}/{action}/idtoo
Kieron
@Kieron - cheers - copy/paste bug ;-p Fixed.
Marc Gravell