Asp.net mvc ActionLink包含斜杠(';/';)并断开链接
我有一个行动链接,如下所示:Asp.net mvc ActionLink包含斜杠(';/';)并断开链接,asp.net-mvc,asp.net-mvc-4,actionlink,Asp.net Mvc,Asp.net Mvc 4,Actionlink,我有一个行动链接,如下所示: <td>@Html.ActionLink(item.InterfaceName, "Name", "Interface", new { name = item.InterfaceName}, null)</td> @Html.ActionLink(item.InterfaceName,“Name”,“Interface”,新的{Name=item.InterfaceName},null) item.InterfaceName是从数据库收集
<td>@Html.ActionLink(item.InterfaceName, "Name", "Interface", new { name = item.InterfaceName}, null)</td>
@Html.ActionLink(item.InterfaceName,“Name”,“Interface”,新的{Name=item.InterfaceName},null)
item.InterfaceName
是从数据库收集的,是FastEthernet0/0
。这将导致创建我的HTML链接,以指向“localhost:1842/Interface/Name/FastEthernet0/0”
。有没有办法使“FastEthernet0/0”
URL友好,这样我的路由就不会混乱?您可以通过替换斜杠来解决这个问题
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建议的,您可能在路由定义中将
名称
作为URL路径的一部分。把它放在一边,它会像URL参数一样正确地发送,URL编码。你应该使用URL.Encode,因为不仅仅是“/”字符,还有其他像“?%”这样的字符也会在URL中被破坏!Url.Encode替换需要编码的每个字符,以下是这些字符的列表:
这将是一个相当大的字符串。请为自己编写一个合适的字符串。因此,请使用:
<td>@Html.ActionLink(item.InterfaceName, "Name", "Interface", new { name = Url.Encode(item.InterfaceName)}, null)</td>
item.InterfaceName.Replace(“/”,“-”)完全错误,例如,“FastEthernet-0/0”将作为“FastEthernet-0-0”传递,并解码为“FastEthernet/0/0”,这是错误的。如果对斜杠进行编码,并将其打印为斜杠,则仍会中断路由。在我的小世界里,我使用思科设备,OPs命名约定是唯一有效的。可能因供应商而异,但我从未见过不同的命名方案。
public ActionResult Name(string interfaceName)
{
//interfaceName is FastEthernet0/0
}