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?
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.
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.
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.
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.
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);
try
{
//do some thing
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert('" +
Server.HtmlEncode(ex.Message) + "')</script>");
}
Does your ex.Message
have any ' characters in it? They may need escaping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With