Escape and Unescape functions for Javascript and ASP.NET


I’ve been working on a chatroom application that requires some AJAX calls to submit messages from user input. Usually, when you want to pass string parameters into the web service, you may do something like this:

escapeDemo_002

This jQuery script calls an asp.net web service method called submitMessage with two parameters sessionIdStr and messageText. The source of parameter messageText is from a input textbox. Since the user may enter any characters (including special characters), and if they have a single quote (‘) in their input, the above statement will break. To resolve this problem, we can simply make use of the escape and unescape functions from javascript.

escapeDemo_003

The escape javascript function simply encode a string to remove all the special characters in order to ensure that messageText parameter is transmitted successfully within the ajax call. For more information about this function, click here.

Now that our messageText paramter can passed successfully to the web service, we may need to do an unscape operation within the web service method to revert it back to the original input. Microsoft has provided us with a very handy library in namescape Microsoft.JScript.GlobalObject.

escapeDemo_004

Now we have the messageText parameter revert back to the original message. We may do our handling code accordingly.

Note that both Javascript and Micorosft.JScript.GlobalObject has escape and unscape operations, you may use the combination in the reverse way (within web service response).

This is it for this short tutorial. Recently, I’ve been dealing with the .NET System.Datetime and Javascript Date conversion, when I have sometime, I’ll share my experience with you here!

, , , , , ,

  1. No comments yet.
(will not be published)