【问题标题】:ActionLink contains slash ('/') and breaks linkActionLink 包含斜杠 ('/') 并断开链接
【发布时间】:2014-04-04 03:40:30
【问题描述】:

我有一个如下的操作链接:

<td>@Html.ActionLink(item.InterfaceName, "Name", "Interface", new { name = item.InterfaceName}, null)</td>

item.InterfaceName 是从数据库中收集的,是FastEthernet0/0。这导致我的 HTML 链接被创建以指向"localhost:1842/Interface/Name/FastEthernet0/0"。有没有办法让"FastEthernet0/0" URL 友好,这样我的路由就不会混淆?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 actionlink


    【解决方案1】:

    您可以通过替换斜线来解决此问题。

    ActionLink(item.InterfaceName.Replace('/', '-'), ....)
    

    在此之后,您的链接将如下所示:localhost:1842/Interface/Name/FastEthernet0-0。 自然,控制器中的 ActionMethod 会出现异常,因为它需要一个命名良好的接口,因此在调用该方法时,您需要恢复替换:

    public ActionResult Name(string interfaceName)
    {
       string _interfaceName = interfaceName.Replace('-','/');
       //retrieve information
       var result = db.Interfaces...
    
    }
    

    另一种方法是构建自定义路由来捕获您的请求:

    routes.MapRoute(
        "interface",
        "interface/{*id}",
         new { controller = "Interface", action = "Name", id = UrlParameter.Optional }
    );
    
    Your method would be:
    
    public ActionResult Name(string interfaceName)
    {
        //interfaceName is FastEthernet0/0
    
    }
    

    此解决方案由 Darin Dimitrov here

    提出

    【讨论】:

      【解决方案2】:

      您可能在路由定义中将name 作为 URL 路径的一部分。把它收起来,它会像 URL 参数一样正确发送,URL 编码。

      【讨论】:

        【解决方案3】:

        您应该使用 Url.Encode,因为不仅是“/”字符,而且像“?#%”这样的其他字符也会破坏 URL! Url.Encode 替换了每个需要编码的字符,下面是这些字符的列表:

        http://www.w3schools.com/TAGs/ref_urlencode.asp

        这将是一个相当大的 String.Replace 为自己写一个合适的。所以使用:

        <td>@Html.ActionLink(item.InterfaceName, "Name", "Interface", new { name = Url.Encode(item.InterfaceName)}, null)</td>
        

        Urlencoded 字符串在作为参数传递给操作方法时会自动解码。

        public ActionResult Name(string interfaceName)
        {
            //interfaceName is FastEthernet0/0
        }
        

        item.InterfaceName.Replace('/', '-') 完全错误,例如“FastEthernet-0/0”将作为“FastEthernet-0-0”传递并解码为“FastEthernet/0/0” "这是错误的。

        【讨论】:

        • 如果你编码一个斜线,并且它被打印为一个斜线,它仍然会破坏路由。在我使用 cisco 设备的小世界中,OP 命名约定是唯一有效的。供应商可能会有所不同,但我从未见过不同的命名方案。
        猜你喜欢
        • 2016-06-05
        • 2011-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 2022-07-07
        相关资源
        最近更新 更多