The ASP.NET AJAX framework gives us an easy way to replace the annoying JavaScript alerts and vastly improve the usability of our applications.
Read The Full Tutorial.
The ASP.NET AJAX framework gives us an easy way to replace the annoying JavaScript alerts and vastly improve the usability of our applications.
Here the code to throw exceptions to test with:
<asp:ScriptManager ID="sm1" runat="server" /> <asp:UpdatePanel runat="server" ID="up1"> <ContentTemplate> <asp:Button runat="server" ID="Button1" Text="Click Me" OnClick="Button1_OnClick" /> </ContentTemplate> </asp:UpdatePanel> protected void Button1_OnClick(object sender, EventArgs e) { throw new Exception("AJAX Error!"); }
If Button1 is clicked, we’ll get a JavaScript alert:

The key to custom error handling in ASP.NET AJAX is the EndRequestEventArgs class, available when handling the endRequest event.
Here you add a div to serve as error message:
<div id="Error" style="visibility: hidden;"> <img src="close.png" onclick="CloseError()" id="CloseButton" alt="Close Button" /> An error has occured while trying to process your request. </div>
Here is some CSS to style the div and close button:
#Error { top: 0px; right: 0px; width: 125px; background-color: yellow; border: solid 1px Black; padding: 10px; font-family: Sans-Serif; font-size: 10pt; position: absolute; margin: 5px; } #CloseButton { float: right; cursor: pointer; }
Here is add some JavaScript to tie it all together: Sys.Application.add_load(AppLoad); function AppLoad() { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest); Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest); } function BeginRequest(sender, args) { // Clear the error if it is visible from a previous request. if ($get(Error).style.visibility == "visible") CloseError(); } function EndRequest(sender, args) { // Check to see if there is an error on this request. if (args.get_error() != undefined) { // If there is, show the custom error. $get(Error).style.visibility = "visible"; // Let the framework know that the error is handled, // so it doesn throw the JavaScript alert. args.set_errorHandled(true); } } function CloseError() { // Hide the error div. $get(Error).style.visibility = "hidden"; }
|