How to show the value of an exception variable in a warning window in asp.net using C #

I have the following code, but the warning window does not appear.

try
{
    do something..          
}
catch(Exception ex)
{
    Response.Write("<script>alert('"+ex+"')</script>");
}

If I use this code, a warning window will appear.

try
{
    do some thing
}
catch (Exception ex)
{           
    Response.Write("<script>alert(\"an error occur\")</script>");
}

How can I display an exception variable in a warning window?

+3
source share
6 answers

If you want to show stacktrace:

Response.Write("<script>alert('"+ Server.HtmlEncode(ex.ToString()) + "')</script>");

or if you want only a message

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

Try something like

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

See class Exclusion class

+2
source
 Dim message = New JavaScriptSerializer().Serialize(rs)
 Dim script = String.Format("alert({0});", message)
 ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", Script, True)
+1

, , . , .

0

You need to be careful and correctly avoid the Javascript line you are generating ... Imagine there are single quotes in the exception message ...

Single quotes ( ') must be escaped ( \')

Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message).Replace("'","\\'" ) + "')</script>");
0
source

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);
0
source

Source: https://habr.com/ru/post/1769489/


All Articles