Friday, May 14, 2010

Url encoding. Problems while opening url with quotes in a different window.

Lately I faced an issue where I was passing a string through query string and the string had quotes and some other special characters. I had to open another modal window where i was supposed to load the new page. Due to quotes it gave me a javascript Error "Expected )".
At once I tried using Uri.EscapeDataString, Uri.EscapeUriString, and HttpUtility.UrlEncode and other similar functions available in c#.
My findings were as follows
original string is: Hello 'Deepa/Hari'
Then,Uri.EscapeDataString("Hello 'Deepa/Hari'") gives: Hello%20'Deepa2FHari'
Uri.EscapeUriString("Hello 'Deepa/Hari'") gives Hello%20'Deepa/Hari'
System.Web.HttpUtility.UrlEncode("Hello 'Deepa/Hari'") gives Hello+'Deepa2FHari'
System.Web.HttpUtility.UrlPathEncode("Hello 'Deepa/Hari'") gives Hello%20'Deepa/Hari'

However JScript.Net's function gives a full proof solution.
Microsoft.JScript.GlobalObject.escape("Hello 'Deepa/Hari'") gives Hello%20%27Deepa/Hari%27
Similarly to unescape, use Microsoft.JScript.GlobalObject.unescape() function.

No comments: