Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Here is what I am doing in jQuery:

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

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

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

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

like image 223
Nick Kahn Avatar asked Apr 20 '12 15:04

Nick Kahn


People also ask

How to encode and decode a URL in JavaScript?

Decoding in Javascript can be achieved using decodeURI function. It takes encodeURIComponent(url) string so it can decode these characters. 2. unescape() function: This function takes a string as a single parameter and uses it to decode that string encoded by the escape() function.

How to decode encoded Value in JavaScript?

To encode a string we need encodeURIComponent() or encodeURI() and to decode a string we need decodeURIComponent() or decodeURI(). Initially, we have used escape() to encode a string but since it is deprecated we are now using encodeURI().

How to convert string into URL in JavaScript?

For your specific example, you would use it like this: const myUrl = "http://example.com/index.html?param=1&anotherParam=2"; const myOtherUrl = new URL("http://example.com/index.html"); myOtherUrl.search = new URLSearchParams({url: myUrl}); console. log(myOtherUrl.

What is difference between decodeURI and decodeURIComponent?

decodeURI(): It takes encodeURI(url) string as parameter and returns the decoded string. decodeURIComponent(): It takes encodeURIComponent(url) string as parameter and returns the decoded string.


1 Answers

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

In JavaScript:

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

And in ASP.NET

_string _id = HttpUtility.UrlDecode(Request.QueryString["id"]);
like image 199
Govind Malviya Avatar answered Nov 14 '22 21:11

Govind Malviya