ActionLink包含斜杠('/')和断开链接

时间:2014-03-03 07:21:40

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

我有一个动作链接,如下所示:

<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友好,以便我的路由不会混淆?

3 个答案:

答案 0 :(得分:3)

你可以通过替换斜杠来解决这个问题。

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

答案 1 :(得分:0)

您可能将name作为路径定义中URL路径的一部分。把它拿走,它将像URL参数一样正确地发送,URL编码。

答案 2 :(得分:0)

您应该使用Url.Encode,因为不仅仅是“/”字符,而其他像“?#%”这样的网址也会破坏! 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字符串在作为参数传递给action方法时会自动解码。

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

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

相关问题