ASP.NET MVC routing with multiple parameters

52 views Asked by At

I have a ManageController with several action methods (Index and Details) which have parameters "group" and "key" and I want to setup my link like this:

http://localhost:49900/Manage/1
http://localhost:49900/Manage/Details/1/sample

But instead the link goes like this

http://localhost:49900/Manage?group=1
http://localhost:49900/Manage/Details?group=1&key=sample

This here is my routing setup:

routes.MapRoute(
            name: "Manage",
            url: "{controller}/{action}/{group}",
            defaults: new { controller = "Manage", action = "Index", group = "" }
        );

routes.MapRoute(
            name: "ManageDetails",
            url: "{controller}/{action}/{group}/{key}",
            defaults: new { controller = "Manage", action = "Details", group = "", key = UrlParameter.Optional }
        );

Controller action methods:

public ActionResult Index(string group)
{
    return View();
}

public ActionResult Details(string group, string key)
{
    return View();
}

Action Links:

<li>
    <a href="@Url.Action("Index", "Manage", new { group = "1" })">Manage</a>
</li>
<li>
    <a href="@Url.Action("Details", "Manage", new { group = "1", key = "sample" })">Manage Details</a>
</li>
1

There are 1 answers

0
Jackdaw On

Consider to use the following routes:

routes.MapRoute(
            name: "ManageDefault",
            url: "{controller}/{group}", // <= the {action} is omitted
            defaults: new { controller = "Manage", action = "Index", group = "" }
        );
routes.MapRoute(
            name: "ManageDetails",
            url: "{controller}/{action}/{group}/{key}",
            defaults: new { controller = "Manage", action = "Details", group = "",
                            key = UrlParameter.Optional }
        );

Your problem in the ManageDefault route declaration: it become universal when using format like "{controller}/{action}/{group}". Therefore, the second template will never take place.

The difference from your code is only removing the {action} section in the first MapRoute(). This should serve the http://localhost:49900/Manage/1 URL format and in the same time the second route template will be used as the default.


In some cases using Attribute Routing may be easier to serve routes like in your case.

See the following post: Attribute Routing in ASP.NET MVC 5