javascript - 使用javascript参数将特殊字符传递给MVC 5 Controller

标签 javascript c# asp.net-mvc

我正在尝试允许用户在 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/

相关文章:

c# - 如何在 ASP .NET Core 中生成和管理 API key

c# - 检查是否使用了c#方法

c# - IModelBinder : access the raw data of the request

c# - 系统.UnauthorizedAccessException : Access to the path denied error

asp.net-mvc - 使用 Asp.net 4.6 的 Azure SignalR 服务

javascript - 如何避免 redux 中的 immutation

javascript - 导致代码更改的 lint 错误但不确定如何继续

javascript - AngularJS 在表中嵌套 ng-repeats

javascript - GraphqlJS-类型冲突-无法使用联合或接口(interface)

c# - 如何通过C#在动态代理中调用泛型函数