2014-03-03 32 views
1

我有一个动作链接,该链接如下: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

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

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 

} 

该解决方案建议由达林季米特洛夫here

0

你可能有name作为扩声路径定义中URL路径的rt。把它拿走,它将被正确地发送,就像一个URL参数,URL编码。

0

您应该使用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( '/', ' - ')是完全错误的,例如, “快速以太网-0/0” 将被称为 “快速以太网-0-0” 传递和解码,以“快速以太网/ 0/0“这是错误的。

+0

如果您编码一个斜线,并将其打印为斜杠,它仍然会破坏路线。在我小小的世界里,我使用cisco设备的地方,OP的命名约定是唯一有效的。可能与供应商有所不同,但我从未见过不同的命名方案。 – Marco