简体   繁体   English

将JavaScript的URL查询字符串值编码为ASP.NET MVC

[英]Encoding URL Query String Value from JavaScript to ASP.NET MVC

I have an app that uses ASP.NET MVC and JavaScript. 我有一个使用ASP.NET MVC和JavaScript的应用程序。 I am generating a URL in my JavaScript like this: 我在JavaScript中生成如下网址:

// Imagine 'filter' is "AT&T".
var v = filter.replace(/'/g, "''");
v = v.replace(/&/g, "%26%");
var t = "(clause eq '" + v + "')";

// At this point, t is "(clause eq 'AT%26%T')"
window.location = '@Url.Content("~/find?")' + 'q=' + t;

In my ASP.NET MVC controller action, I have the following: 在我的ASP.NET MVC控制器操作中,我具有以下内容:

public ActionResult Find(int? id, string q)
{
  // do stuff
}

If I set a breakpoint in the Find action, I notice that q is the following: 如果在“ Find操作中设置了断点,则会注意到q如下:

(clause  eq 'AT&%T')

I'm not sure why. 我不知道为什么。 I need it to be (clause eq 'AT%26%T') . 我需要它(clause eq 'AT%26%T') What am I doing wrong? 我究竟做错了什么? I understand its some encoding issue. 我了解其一些编码问题。

The reason for this is that your encoded ampersand %26 is UrlDecoded serverside back to & . 这样做的原因是,您的编码后的&符号%26在服务器端返回了& UrlDecoded。 If you want to keep the url encoded version you need to escape the percent sign % too with its encoded equivalent %25 : 如果要保留url编码的版本,则还需要使用与其等效的%25来对百分号%进行转义:

v = v.replace(/&/g, "%2526%");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM