如何在 jQuery/JavaScript 中编码 URL 并在 ASP.NET 中解码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10248722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:10:52  来源:igfitidea点击:

How to encode a URL in jQuery/JavaScript and decode in ASP.NET

c#javascriptjqueryasp.neturlencode

提问by Nick Kahn

How do you safely encode a URL using JavaScript such that it can be put into a GET string?

如何使用 JavaScript 安全地对 URL 进行编码,以便将其放入 GET 字符串中?

Here is what I am doing in jQuery:

这是我在 jQuery 中所做的:

var url = "mynewpage.aspx?id=1234";
$(location).attr('href', url);

And in the ASP.NET page_load, I am reading this:

在 ASP.NET page_load 中,我正在阅读:

_string _id = Request.QueryString["id"].ToString();

How can I encode the id in jQuery/JavaScript and decode in ASP.NET (C#)?

如何在 jQuery/JavaScript 中编码 id 并在 ASP.NET (C#) 中解码?

回答by Govind Malviya

Use encodeURIComponent(str)in JavaScript for encoding and use HttpUtility.UrlDecodeto decode a URL in ASP.NET.

使用encodeURIComponent(str)在JavaScript编码和使用HttpUtility.UrlDecode解码在ASP.NET的URL。

In JavaScript:

在 JavaScript 中:

var url = "mynewpage.aspx?id="+encodeURIComponent(idvalue);
$(location).attr('href', url);

And in ASP.NET

在 ASP.NET 中

_string _id = HttpUtility.UrlDecode(Request.QueryString["id"]);

回答by veeTrain

I've always found this sitewonderfully useful for figuring out which encoding I should be using (probably encodeURIor encodeURIComponent). You should be able to find what you want to use there.

我一直发现这个站点对于确定我应该使用哪种编码(可能encodeURIencodeURIComponent)非常有用。您应该能够在那里找到您想要使用的内容。

I'm not as familiar with the ASP.NET side of things. These guysprobably already have a great answer for you.

我不太熟悉 ASP.NET 方面的事情。这些人可能已经为您提供了很好的答案。