5

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#)?

1

2 Answers 2

10

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"]);
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.