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.

Monday, May 3, 2010

Stopping a postback on client side with Ajax

Requirement was - on click of a button I wanted to get an alert and then based on logic i either wanted to do a postback or stop it.
Initial code
btn.onClientClick="return validate();"
Javascript code looked like this
function validate()
{
alert('some message');
if(some condition)
return true;
else
return false;
}
I had ajax post back on my button click which i wanted to stop when false is returned from validate function. But with above code it never posted back not even if the function returned true.
Ok! What went wrong
The code btn.OnClientClick = "return validate();" would get rendered as
input type="submit" onclick="return validate(); __doPostback(..)"
So what is happening is whether the javascript function returns true or false it doesnt matter, __doPostBack will never get called.
Lets now change it to make it work
btn.OnClientClick="if(!return validate()) return false;"
This renders
input type="submit" onclick=if(!validate()) return false; __doPostBack(..)"
So only when the validate() function returns false will it execute the first statement and will return from there else it will go to __doPostBack and cause a post back to happen.
Took me some time to figure this out and it just goes to prove that common sense is actually not so common ;-)