javascript 在asp.net中通过javascript警报显示异常消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6450235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:42:43  来源:igfitidea点击:

Display exception message through javascript alert in asp.net

c#javascriptasp.net

提问by rdp

I am trying to show exception message through javascript alert box.

我正在尝试通过 javascript 警报框显示异常消息。

Here is the sample code.

这是示例代码。

public static void HandleException(Page page, Exception ex)
{
    string message = ex.Message.ToString();
    ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", "alert('"+message+"');", true);

}

It runs if i give literal values for the string variable. e.g.

如果我为字符串变量提供文字值,它就会运行。例如

string message = "Hello World";

But it fails if I give message = ex.Message;

但是如果我给 message = ex.Message; 就会失败。

Any Idea?

任何的想法?

回答by Darin Dimitrov

You need to encode it, for example using JavaScriptSerializerbecause if the message contains some escape characters like 'or "this will definitely break your javascript:

您需要对其进行编码,例如使用JavaScriptSerializer因为如果消息包含一些转义字符,例如'或者"这肯定会破坏您的javascript:

var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
var script = string.Format("alert({0});", message);
ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", script, true);

回答by Bibhu

try    
{    
    //do some thing    
}    
catch (Exception ex)
{    
    Response.Write("<script language='javascript'>alert('" + 
        Server.HtmlEncode(ex.Message) + "')</script>");    
}

回答by Paul McLean

Does your ex.Messagehave any ' characters in it? They may need escaping.

ex.Message有任何 ' 字符吗?他们可能需要逃跑。