I am setting a value in the cookie using JavaScript and getting the contents of the cookie in the code behind.
But the problem is if I am storing the string with some special characters or whitespace characters, when I am retrieving the contents of the cookie the special symbols are getting converted into ASCII equivalent.
For example, if I want to store Adam - (SET)
in cookie , its getting converted into Adam%20-%20%28SET%29
and getting stored and when I am retrieving it I get the same Adam%20-%20%28SET%29
. But I wan tot get this Adam - (SET)
in the code behind.
How I get this. Please help.
I am setting a value in the cookie using JavaScript and getting the contents of the cookie in the code behind.
But the problem is if I am storing the string with some special characters or whitespace characters, when I am retrieving the contents of the cookie the special symbols are getting converted into ASCII equivalent.
For example, if I want to store Adam - (SET)
in cookie , its getting converted into Adam%20-%20%28SET%29
and getting stored and when I am retrieving it I get the same Adam%20-%20%28SET%29
. But I wan tot get this Adam - (SET)
in the code behind.
How I get this. Please help.
Share Improve this question edited Jul 12, 2012 at 8:09 haylem 22.7k3 gold badges69 silver badges96 bronze badges asked Jul 12, 2012 at 8:06 BibhuBibhu 4,0914 gold badges35 silver badges64 bronze badges 2- You want to do the retrieving in c# ? – Gerald Versluis Commented Jul 12, 2012 at 8:08
- Can you clarify whether you need to decode that in JS or C#? – carlosfigueira Commented Jul 12, 2012 at 8:11
4 Answers
Reset to default 2In C#
Use:
String decoded = HttpUtility.UrlDecode(EncodedString);
HttpUtility.UrlDecode() is the underlying function used by most of the other alternatives you can use in the .NET Framwework (see below).
You may want to specify an encoding, if necessary.
Or:
String decoded = Uri.UnescapeDataString(s);
See Uri.UnescapeDataString()'s documentation for some caveats.
In JavaScript
var decoded = decodeURIComponent(s);
Before jumping on using unescape
as remended in other questions, read decodeURIComponent vs unescape, what is wrong with unescape? . You may also want to read What is the difference between decodeURIComponent and decodeURI? .
You can use the unescape
function in JS to do that.
var str = unescape('Adam%20-%20%28SET%29');
You are looking for HttpUtility.UrlDecode()
(in the System.Web namespace, I think)
In javasrcipt you can use the built-in decodeURIComponent, but I suspect that the string encoding is happening when the value is sent to server so the C# answers are what you want.