Brian Hooper
Brian Hooper

Reputation: 22074

How to clean up an exception string so it can be displayed via Javascript Alert?

I'm attempting to display an exception string in the time-honoured way:-

Page page = HttpContext.Current.CurrentHandler as Page;

if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
    page.ClientScript.RegisterClientScriptBlock(
                  typeof(Alert),
                  "alert",
                  "<script type=\"text/javascript\">alert(\"Fred\");</script>");
}

This works perfectly fine and displays the message as expected. If, however, I use a string supplied by some other part of the program:-

    page.ClientScript.RegisterClientScriptBlock(
       typeof(Alert),
       "alert",
       "<script type=\"text/javascript\">alert(\"" + error_message + "\");</script>");

no popup is displayed and an error occurs,

Unterminated String Constant

The string contains a deplorable number of control characters but not, as far as I can see, any " or ' characters. Is there a function that can be invoked to clean up a string so that it can be displayed by a Javascript Alert? This fellow here had a similar problem but no general solution was forthcoming.

Upvotes: 2

Views: 603

Answers (1)

DGibbs
DGibbs

Reputation: 14618

You need to serialize the message before displaying it as it will likely contain characters that are breaking your JS. You can use the JavaScriptSerializer class

For example:

var errorMsg = new JavaScriptSerializer().Serialize(error_message);
page.ClientScript.RegisterClientScriptBlock(
   typeof(Alert),
   "alert",
   "<script type=\"text/javascript\">alert(\"" + errorMsg + "\");</script>");

Upvotes: 3

Related Questions