2

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.

haylem
  • 22,460
  • 3
  • 67
  • 96
Bibhu
  • 4,053
  • 4
  • 33
  • 63

4 Answers4

1

In 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 recommended 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? .

Community
  • 1
  • 1
haylem
  • 22,460
  • 3
  • 67
  • 96
  • @Bibhu: You're welcome, glad it helps. If you are satisfied with one of the answers, please use the tick symbol under the vote counter to accept it. – haylem Jul 12 '12 at 08:21
0

You can use the unescape function in JS to do that.

var str = unescape('Adam%20-%20%28SET%29');
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
0

You are looking for HttpUtility.UrlDecode() (in the System.Web namespace, I think)

Gerald Versluis
  • 30,492
  • 6
  • 73
  • 100
0

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.

RobG
  • 142,382
  • 31
  • 172
  • 209