Tuesday, May 20, 2008

Using asp:Localize within Javascript strings

A common requirement is to customize the strings displayed in Javascript alert and confirm boxes, such as when providing a multilingual user interface for a web application.

Most developers would use the asp:Localize for this purpose and the problem associated with it is when a single quote is used within the resource file and it gets inserted by ASP.NET into the Javascript string declaration or assignment... it makes the Javascript go haywire due to the appearance of a string terminator within the string literal.

A workaround to this issue would be to create an asp:HiddenField control on the page that reads from the resource file for it's value - our Javascript then gets the control using a $get with a ControlName.ClientID and accessing the value property. Although it's a little more work than using the asp:Localize control within the Javascript string directly, it's a more robust approach.

No comments: