views:

35

answers:

2

i need to show the server exception in client browser, but it seems there are some illegal characters inside the exp.Message which makes the client script to raise "unterminated string literal" error. any idea to make strings such as exp.Message safe for client scripts?

    catch (Exception exp)
    {
      string __script = string.Format(@"alert('{0}');", exp.Message);
      ScriptManager.RegisterStartupScript(this, this.GetType(), "theError", __script, true);
    }
A: 

Try HttpUtility.HtmlEncode

using System.Web;

...

var encodedMessage = HttpUtility.HtmlEncode(exp.Message);
string __script = string.Format(@"alert('{0}');", encodedMessage);
Albin Sunnanbo
unfortunately HtmlEncode did not help in this issue. i checked the return value of HtmlEncode. it seems that some illegal characters (such as single quotation marks) still there.
syntaxcheck
A: 

after a lot of search, finally found a solution in rick strahl's blog: EncodeJsString

syntaxcheck