2
votes

Asking for the best way to address this issue:

in my controller I have the following action

public ActionResult Member(string id){return View();}

another action in the same controller

public ActionResult Archive(string year){return View();}

in my global.asax

routes.MapRoute(
            "Archive",                                              // Route name
            "{controller}/{action}/{year}",                           // URL with parameters
            new { controller = "Home", action = "Index", year = "" }  // Parameter defaults
        );

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

if I call this url mysite.com/archive/2009 this works because the action expecting parameter with a name "year" and the first route schema works with this request. But if I call this url mysite.com/member/john it will result in this url mysite.com/member?id=john So it looks like if my first route in global.asax have the same construction but different parameter name, the one with the right parameter name will have the right url (mysite.com/archive/2009) but for the other won't. How can I solve this issue? I can change the route table to expect a generic parameter name like "param", but I need to change all the signature of the action to "param" as well and it is not very descriptive (param instead year or param instead id).

1

1 Answers

1
votes

Try this:

routes.MapRoute(
            "Archive",                                              // Route name
            "Home/Member/{id}",                           // URL with parameters
            new { controller = "Home", action = "Member", id = "" }  //
Parameter defaults
        );

routes.MapRoute(
            "Archive",                                              // Route name
            "{controller}/{action}/{year}",                           // URL with parameters
            new { controller = "Home", action = "Index", year = "" }  // Parameter defaults
        );

You are allowed to use literals in the second parameter, and they will act as filters. The more specific your route is, the closer you need to put it to the top of the route configuration, the routing system will choose the first route that matches.

Here is a link to more detailed background information. Some of the syntax has changed since the article was written but the basic rules seem up to date.