Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems encoding\decoding strings JS <-> C#

I have a problem in JS encoding and then decoding in the C# server. I use javascript encode() function - but when i have special chars like +, the C# has httputility.urldecode() -> and it converts it as if it was SPACE char.

What is the best way to communicate JS encoding and C# decoding?

I have <a href='javascript:foo(escape('hello +'))' />

function foo(data)
{
$.ajax({ url: "http:/....." + data, dataType: 'html', context: document.body
...
...
}

I debugged the server, and I get 'hello++' - it doesnt know which + is which (space or +) Thank you!

like image 933
Himberjack Avatar asked Sep 03 '26 22:09

Himberjack


2 Answers

Javascript encode does html encoding. Since + is valid in HTML, it does nothing to the +.

However, you are passing this string through the URL - + on a URL means an encoded space.

You need to use the javascript encodeURIComponent if you want the + to be encoded correctly for consumption on the server side:

<a href='javascript:foo(encodeURIComponent('hello +'))' />

You need to understand that HTML encoding and URL encoding are different things.

like image 121
Oded Avatar answered Sep 05 '26 10:09

Oded


javascript:

escape(string);

C#:

Microsoft.JScript.GlobalObject.unescape(string);

this combination works fine for me.

like image 27
Kin Avatar answered Sep 05 '26 12:09

Kin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!