3

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\")</script>");
}

How can I display the exception variable in an alert box?

krillgar
  • 12,596
  • 6
  • 50
  • 86
Sheetal Inani
  • 128
  • 3
  • 5
  • 16

6 Answers6

6

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>");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

Try something like

Response.Write("<script>alert('"+ex.Message+"')</script>"); 

Have a look at the class Exception Class

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • 2
    The message should be HtmlEncoded. it could contain " or other charaters that will make the html rendering behave different from the intent – Rune FS Oct 14 '10 at 07:59
1
 Dim message = New JavaScriptSerializer().Serialize(rs)
 Dim script = String.Format("alert({0});", message)
 ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", Script, True)
0

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);
Atur
  • 1,712
  • 6
  • 32
  • 42
rehu
  • 11
  • 2
0

Please check whthr you r using update panel in that page.It may sometimes work if the update panel is there.

kbvishnu
  • 14,760
  • 19
  • 71
  • 101
0

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>");
tsimbalar
  • 5,790
  • 6
  • 37
  • 61