Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Display exception message through javascript alert in asp.net

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

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;

Any Idea?

like image 361
rdp Avatar asked Jun 23 '11 06:06


People also ask

How to display an alert message in JavaScript?

One useful function that's native to JavaScript is the alert() function. This function will display text in a dialog box that pops up on the screen. Before this function can work, we must first call the showAlert() function. JavaScript functions are called in response to events.

How can I call JavaScript alert from code behind in asp net?

To display JavaScript alert message from code behind we can do by using ScriptManager. RegisterStartupScript() method. This method will allow us to show alert message direclty from code behind or we can call javascript function from code behind in asp.net.

How to popup confirm message box in JavaScript?

Confirm Box In this scenario, use the built-in function confirm() . The confirm() function displays a popup message to the user with two buttons, OK and Cancel . The confirm() function returns true if a user has clicked on the OK button or returns false if clicked on the Cancel button.

What is alert and prompt in JavaScript?

An alert box is used if we want the information comes through to the user. A prompt box is used when we want the user to input a value before entering a page.

3 Answers

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

var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
var script = string.Format("alert({0});", message);
ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", script, true);
like image 53
Darin Dimitrov Avatar answered Oct 18 '22 16:10

Darin Dimitrov

    //do some thing    
catch (Exception ex)
    Response.Write("<script language='javascript'>alert('" + 
        Server.HtmlEncode(ex.Message) + "')</script>");    
like image 3
Bibhu Avatar answered Oct 18 '22 16:10


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

like image 2
Paul McLean Avatar answered Oct 18 '22 16:10

Paul McLean