how to show exception variable value in alert box in asp.net using C#
I have the following code, but the alert box is not displaying.
try
{
do something..
}
catch(Exception ex)
{
Response.Write("<script>alert('"+ex+"')</script>");
}
If I use this code, the alert box appears.
try
{
do some thing
}
catch (Exception ex)
{
Response.Write("<script>alert(\"an error occur\"开发者_JAVA技巧)</script>");
}
How can I display the exception variable in an alert box?
If you want to show the stacktrace:
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.ToString()) + "')</script>");
or if you want only the message
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message) + "')</script>");
Try something like
Response.Write("<script>alert('"+ex.Message+"')</script>");
Have a look at the class Exception Class
Dim message = New JavaScriptSerializer().Serialize(rs)
Dim script = String.Format("alert({0});", message)
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", Script, True)
Please check whthr you r using update panel in that page.It may sometimes work if the update panel is there.
You need to be careful and properly escape the Javascript string you are generating ... Imagine there are single quotes in the Exception's message ...
Single-quotes ('
) need to be escaped (\'
)
Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message).Replace("'","\\'" ) + "')</script>");
This solved my problem:
string jscriptCustInfo = "<script type='text/javascript' language='javascript'>";
jscriptCustInfo = jscriptCustInfo + "alert('Dividend Posting Done, Batch No: "+lblBatch.Text+"');";
jscriptCustInfo = jscriptCustInfo + "</script>";
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", jscriptCustInfo, false);
精彩评论