简体   繁体   English

字符串中包含回车符时,RegisterStartupScript Alert错误

[英]RegisterStartupScript Alert Error when carriage return is in the string

I have RegisterStartupScript in the code-behind class to alert error message -- it works fine except when the error has line feeds or carriage returns (I think). 我在代码隐藏类中有RegisterStartupScript来警告错误消息-除非错误有换行符或回车符(我认为),否则它运行正常。 Here is the snippet: 这是代码段:

The commented code works fine! 注释的代码工作正常!

catch (Exception ex)
        {
           //Page.ClientScript.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Failure", "alert('ERROR: '), true);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "System Error", "alert('" + ex.Message.Replace("'", "\\'") + "');", true);
        }

Line terminators are not allowed in js strings. js字符串中不允许使用行终止符。 Eliminate the line terminators (carriage returns, new line symbols etc.) using regular expressions: 使用正则表达式消除行终止符(回车,换行符等):

var errorMsg = Regex.Replace(ex.Message, 
    @"[\u000A|\u000D|\u2029\u2028|\u000D\u000A]", " ");

Page.ClientScript.RegisterStartupScript(this.GetType(), "System Error", 
    String.Format("alert('{0}');", errorMsg), true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM