【问题标题】:how do I add a url parameter to a routelink in asp.net mvc?如何将 url 参数添加到 asp.net mvc 中的 routelink?
【发布时间】:2009-05-03 19:54:41
【问题描述】:

所有,我的情况是我有基本路线,加上其他一些简单的路线:

routes.MapRoute(
                "Default",                                              
                "{controller}/{action}/{id}",                           
                new { controller = "Home", action = "Index", id = 1}
            );

所以以下网址有效:http://somesite.com/tags/index/1

但是,我的一些索引页面采用以下方式的 url 参数:

http://somesite.com/tags/index/1?when=lastmonth

如何使用 Html.RouteLink 链接到这个?

不能添加“?”像这样在全局 asax 文件中路由:

routes.MapRoute("TagsWhen", "Tags/index/{id}?when={when}",
      new {controller = "Tags", action = "Index", id = "", when = ""});

如果这条路线有效,我可以使用以下方法链接到它:

Html.RouteLink(string.Format("{0} ", link.Rating), "LinksWhen", 
               new {id=link.ReferenceId, when=Model.When})

但事实并非如此!所以我不确定如何使用 Html.RouteLink 生成http://somesite.com/tags/index/1?when=lastmonth

【问题讨论】:

    标签: c# .net asp.net asp.net-mvc


    【解决方案1】:

    刚刚自己找到了解决方案。你可以做一个常规的 Html.RouteLink 和任何你没有映射到 global.asax 中的 url 它作为 url 参数添加的对象属性。

    所以使用这条路线:

        routes.MapRoute(
            "Links",                                              
            "Links/details/{id}",                           
            new { controller = "Links", action = "Details", id = ""} defaults
        );
    

    还有这条路线链接:

    Html.RouteLink("Link Text", "Links", 
            new {id=link.ReferenceId, when=Model.When })
    

    生成正确的网址:

    http://localhost:2535/Links/details/1?when=onemonth

    【讨论】:

    • 您应该仍然可以基于 ActionLink。我不知道为什么马修的解决方案不起作用?我使用 ActionLink 和他做同样的事情,我有一个网址:.../delete/124?otherId=5
    • 另外,如果您使用 RouteLink,则添加另一个依赖项,“Links”路由名称必须始终存在,并且您将名称绑定到 ref。在您看来(如果您确实更改了名称,您也会遇到异常)。因为你有一条标准路线,ActionLink 就可以了,然后你不需要为它自己的单独命名路线编写代码。
    • 我很好奇。既然可以有一个漂亮的网址,为什么还要创建一个“丑陋”的网址?!
    【解决方案2】:

    Matthew 的方法可能不起作用,因为他最后需要另一个 null 参数,否则它将路由值作为 html 属性传递。 :)

    <%= Html.ActionLink("Link text", "Index", "Home", new { id = 1, when = "lastmonth" }, null) %>
    

    你想出的最后一个MapRoute() 应该可以很好地对付它。

    【讨论】:

      【解决方案3】:

      我没有一台可以测试这个的电脑,但我想不到

      <%= Html.ActionLink("Link text", "Index", "Home", new { id = 1, when = "lastmonth" } %>
      

      您无需在 global.asax.cs 文件中的路由中指定可选参数。默认情况下,任何不匹配的内容都会被放入查询字符串中。

      【讨论】:

      • 但这不会生成不正确的网址吗?
      • 刚刚试了一下,它会生成:somesite.com/tags/index?when=lastmonth 并且不添加 id...
      • 问题具体是RouteLink,而不是ActionLink
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 2017-11-15
      • 2020-10-02
      相关资源
      最近更新 更多