Monday, October 30, 2006

HttpUtility.UrlEncode is NOT equivalent to javascript "escape"

A few days ago, I posted about how to fix a "," problem in an very good autocomplete control.

As part of the solution I proposed to use "HttpUtility.UrlEncode" thinking that it was equivalent to javascript "escape" function, but.. it is not equivalent!

For example, HttpUtility.UrlEncode encodes the " " (whitespace) to "+", while javascript encode escapes the " " to "%20".

The same things goes for encodeURI in case you were wondering (and please don't even bother trying with HttpUtility.HtmlEncode, its purpose is completely different)

The answer? good old JScript.NET (in the server side):


The documentation reads "This method supports the .NET Framework infrastructure and is not intended to be used directly from your code." but, since there is no other option, and I NOT going to implement this by myself, i think this is the best option available.

Do you know any other way to do it? would you please share it with me?


Jason Phillips said...
This comment has been removed by the author.
Jason Phillips said...
This comment has been removed by the author.
Jason Phillips said...

My situation was sort of similiar but I was encoding a server textbox using javascript document.getElembentByID('TextBox.ClientID').value = encode(doc.geElementBYId('TextBox1.ClientID').value). But i needed to to convert it back on the server side to html text. The HtmlDecode utility was useless converting escape back to recognize(see Problem code) but HttpURLDecode works

My Problem code was listed below:
string htmlstring = HttpUtility.HtmlDecode(TextBox1.Text) (was useless)

Work Around

htmlstring = HttpUtility.URLDecode(TextBox1.Text, System.Text.Encoding.Default);