Wednesday, March 9, 2011

How To: Encode a JavaScript string in .NET To Escape Characters (i.e. Single Quotes) Automatically

There is a handy new Utility method new to the .NET Framework 4.0 found in the System.Web.HttpUtility namepsace called HttpUtility.JavaScriptStringEncode. It allows you the developer to create any string needed and URL encodes it to be usable by JavaScript.

Ever tried making a Utility method to create a script to be registered with the page in ASP.NET that will popup a JS alert box and takes a message? Ever see what happens when you try and place a single quote in the value like "The value 'x' is not allowed"? The JS will error out on the page with a " Expected ')' " type error message. If you use the utility mentioned above, the encoding is done for you and injects any needed escape characters. The line of code below shows how this might be done in .NET code:

Dim Message As String = "The value 'x' is not allowed"
'URL Encode the message prior to registering with the page
Dim JsAlert As String = "alert('""" & HttpUtility.JavaScriptStringEncode(Message) & """');"
ClientScript.RegisterStartupScript(Page.GetType(), "AlertJsFunction", JsAlert)

3 comments: