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#)?
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.
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().
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.
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.
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"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With