我正在尝试允许用户在 MVC 应用程序中编辑名称。
Controller 函数有这个签名:
[Route("function/edit/{id:int}/{name}/{sortorder:int}")]
public ActionResult Edit(int id, string name, int sortorder)
{...}
我在 Javascript 中这样调用它:
window.location.href = "@Url.Action("Edit", "Function")" + "/" + id + "/" + name + "/" + order;
一切正常,直到名称包含“/”或名称以“.”结尾。然后我得到一个“找不到资源”。从服务器。 这是完全有道理的,因为 '/' 和 '.'字符正确地混淆了路由...
但是我应该怎么做呢??我想允许 '/' 和 '.'在名字中。
最佳答案
您需要对数据进行编码,以便正确传递 /
等字符。为此,您应该使用 encodeURIComponent
功能:
window.location.href =
"@Url.Action("Edit", "Function")" + "/" + id + "/" +
encodeURIComponent(name) + "/" + order;
比如这是编码前后的区别:
var test = "this.is/a test";
alert(test);
alert(encodeURIComponent(test));
除此之外,您的 MVC 应用程序还由于解码 URL 的方式而出现问题。一种解决方案是重新排序路由中的参数,使 name
值最后并为其提供一个包罗万象的修饰符:
[Route("function/edit/{id:int}/{sortorder:int}/{*name}")]
这会强制 MVC 路由选择最后一部分作为 name
的完整值。
关于javascript - 使用javascript参数将特殊字符传递给MVC 5 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28627387/