Tuesday, February 19, 2013

How to encode JavaScript string to escape characters such as single quotes in .NET


When registering JavaScript functions or calling JavaScript functions from code behind there might me some specials characters such as single quotes, new line characters. These kinds of characters will causes for errors such as ” Unexpected identifier” , “Unterminated String constant” or “Expected ')'” type errors. To avoid these errors string encoding has to be done.

In .Net framework 4 a new method has been introduced to cater these types of errors under the System.Web.HttpUtility namespace called HttpUtility.JavaScriptStringEncode. This method does the encoding and injects necessary escape characters.

As an example, to show an alert which includes single quotes we have to use the encoding.


  string message = "The value 'x' is not allowed";

  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", string.Format("alert('{0}');", message), true); // This will give an error

  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", string.Format("alert('{0}');", HttpUtility.JavaScriptStringEncode(message)), true); // JavaScript encoding has been done.


No comments:

Post a Comment