MVC 中使用破折号路由可选参数

发布于 2024-09-02 09:28:07 字数 1085 浏览 5 评论 0原文

我做了这样的路由定义:

 routes.MapRoute("ProductSearch", "Search-{MainGroup}-{SubGroup}-{ItemType}",
   new {
    controller = "Product",
    action = "Search",
    MainGroup = "", SubGroup = "", ItemWebType = ""});

如果参数为空,它将不起作用。 实际上它解析了 url,因此 Url.Action 方法解析了路径“Search-12--”,但链接不起作用,因此页面的 GET 不起作用

使用斜线,它正在工作 Url.Action 方法使“Search” /12"

"Search/{MainGroup}/{SubGroup}/{ItemType}"

是否可以以某种方式纠正它?

我用默认的mvc项目制作了一个示例: 仅添加: 默认路由之前:

    routes.MapRoute(DefaultSearch", "Search-{MainGroup}-{Subgroup}-{ItemType}",
        new {controller = "Home",action = "About", MainGroup = "", 
              Subgroup = "", ItemType = ""});

在 Home/index.aspx 中:

<a href="<%=Url.Action("About", "Home", new {maingroup = "2", subgroup = "", itemType = ""}) %>">
    Search</a>

在 HomeController 中:

public ActionResult About(string maingroup, string subgroup, string itemtype)
{
  return View();
}

单击链接和 404

I've made an routing definition like this:

 routes.MapRoute("ProductSearch", "Search-{MainGroup}-{SubGroup}-{ItemType}",
   new {
    controller = "Product",
    action = "Search",
    MainGroup = "", SubGroup = "", ItemWebType = ""});

It is not working if the parameters are empty.
Actually it resolves the url, so Url.Action method resolves the path "Search-12--" but the link is not working, so the GET of the page is not working

With slashes it is working the Url.Action method makes "Search/12"

"Search/{MainGroup}/{SubGroup}/{ItemType}"

Is it somehow possible to correct it?

I made a sample with the default mvc project:
Only added:
before default route:

    routes.MapRoute(DefaultSearch", "Search-{MainGroup}-{Subgroup}-{ItemType}",
        new {controller = "Home",action = "About", MainGroup = "", 
              Subgroup = "", ItemType = ""});

in Home/index.aspx:

<a href="<%=Url.Action("About", "Home", new {maingroup = "2", subgroup = "", itemType = ""}) %>">
    Search</a>

In HomeController:

public ActionResult About(string maingroup, string subgroup, string itemtype)
{
  return View();
}

Click on the link and 404

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怀里藏娇 2024-09-09 09:28:07

你用什么版本?在 mvc 2 中,您可以使用 UrlParameter.Optional 作为路由的默认值。

What version do you use? in mvc 2 you can use UrlParameter.Optional as default values for routes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文