具有多个参数的 ASP.NET MVC 路由

问题描述 投票:0回答:1

我有一个带有多个操作方法(

ManageController
Index
)的
Details
,其中有参数“group”和“key”,我想像这样设置我的链接:

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

但是链接是这样的

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

这是我的路由设置:

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 }
        );

控制器动作方法:

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

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

行动链接:

<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>
asp.net-mvc asp.net-mvc-routing
1个回答
0
投票

考虑使用以下路线:

routes.MapRoute(
            name: "ManageDefault",
            url: "{controller}/{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 }
        );

您在

ManageDefault
路线声明中的问题:当使用像
"{controller}/{action}/{group}"
这样的格式时,它变得通用。因此,第二个模板永远不会发生。

与您的代码的区别仅在于删除第一个

{action}
中的
MapRoute()
部分。这应该服务于
http://localhost:49900/Manage/1
,同时第二个路由模板将用作默认值。

© www.soinside.com 2019 - 2024. All rights reserved.