Skip to content Skip to sidebar Skip to footer

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.M

Solution 1:

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

Solution 2:

try    
{    
    //do some thing    
}    
catch (Exception ex)
{    
    Response.Write("<script language='javascript'>alert('" + 
        Server.HtmlEncode(ex.Message) + "')</script>");    
}

Solution 3:

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

Post a Comment for "Display Exception Message Through Javascript Alert In Asp.net"