Customizing Error Handling for ASP.NET UpdatePanel Controls
When an error occurs during partial-page updates in UpdatePanel controls, the default behavior is that a browser message box is displayed with an error message. This tutorial shows you how to customize how the error is presented to the user and how to customize the error message.
Prerequisites
To implement the procedures in your own development environment you need:
Microsoft Visual Studio 2005 or Microsoft Visual Web Developer Express.
An AJAX-enables ASP.NET Web site.
Customizing Error Handling in Server Code
To begin, you will customize error handling by using server code in the page.
To customize error handling in server code
Create a new page and switch to Design view.
In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control and the UpdatePanel control to add them to the page.
Add the following controls inside the UpdatePanel control:
Two TextBox controls.
A Label control
A Button control. Set its Text property to Calculate.
Some text inside the UpdatePanel control.
Double-click the Calculate button and add the following code for its event handler:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Try Dim a As Int32 a = Int32.Parse(TextBox1.Text) Dim b As Int32 b = Int32.Parse(TextBox2.Text) Dim res As Int32 = a / b Label1.Text = res.ToString() Catch ex As Exception If (TextBox1.Text.Length > 0 AndAlso TextBox2.Text.Length > 0) Then ex.Data("ExtraInfo") = " You can't divide " & _ TextBox1.Text & " by " & TextBox2.Text & "." End If Throw ex End Try End Sub
protected void Button1_Click(object sender, EventArgs e) { try { int a = Int32.Parse(TextBox1.Text); int b = Int32.Parse(TextBox2.Text); int res = a / b; Label1.Text = res.ToString(); } catch (Exception ex) { if (TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0) { ex.Data["ExtraInfo"] = " You can't divide " + TextBox1.Text + " by " + TextBox2.Text + "."; } throw ex; } }
The code contains a try-catch statement. In the try block, the code performs division on the values entered into the text boxes. If the operation fails, code in the catch block adds the extra string information in ExtraInfo to the exception and then re-throws the exception without handling it.
Switch to Design view and select the ScriptManager control.
In the toolbar of the Properties window, click the Events button and then double-click the AsyncPostBackError box to create a handler for that event.
Add the following code to the AsyncPostBackError event handler:
Protected Sub ScriptManager1_AsyncPostBackError(ByVal sender As Object, ByVal e As System.Web.UI.AsyncPostBackErrorEventArgs) If (e.Exception.Data("ExtraInfo") <> Nothing) Then ScriptManager1.AsyncPostBackErrorMessage = _ e.Exception.Message & _ e.Exception.Data("ExtraInfo").ToString() Else ScriptManager1.AsyncPostBackErrorMessage = _ "An unspecified error occurred." End If End Sub
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) { if (e.Exception.Data["ExtraInfo"] != null) { ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message + e.Exception.Data["ExtraInfo"].ToString(); } else { ScriptManager1.AsyncPostBackErrorMessage = "An unspecified error occurred."; } }
The code checks whether the ExtraInfo data item is defined for the exception. If it is, the AsyncPostBackErrorMessage property is set to the string value. Otherwise, a default error message is created.
Save your changes and then press CTRL+F5 to view the page in a browser.
Add a number greater than zero to each text box and then click the Calculate button to demonstrate a successful postback.
Change the second text box value to 0 and then click the Calculate button to create an error condition.
The browser displays a message box that contains the message that was set in the server code.
Note
The style of the message box depends on what browser you are using, but the message is the same in all browsers.
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Try Dim a As Int32 a = Int32.Parse(TextBox1.Text) Dim b As Int32 b = Int32.Parse(TextBox2.Text) Dim res As Int32 = a / b Label1.Text = res.ToString() Catch ex As Exception If (TextBox1.Text.Length > 0 AndAlso TextBox2.Text.Length > 0) Then ex.Data("ExtraInfo") = " You can't divide " & _ TextBox1.Text & " by " & TextBox2.Text & "." End If Throw ex End Try End Sub Protected Sub ScriptManager1_AsyncPostBackError(ByVal sender As Object, ByVal e As System.Web.UI.AsyncPostBackErrorEventArgs) If (e.Exception.Data("ExtraInfo") <> Nothing) Then ScriptManager1.AsyncPostBackErrorMessage = _ e.Exception.Message & _ e.Exception.Data("ExtraInfo").ToString() Else ScriptManager1.AsyncPostBackErrorMessage = _ "An unspecified error occurred." End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Partial-Page Update Error Handling Example</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:TextBox ID="TextBox1" runat="server" Width="39px"></asp:TextBox> / <asp:TextBox ID="TextBox2" runat="server" Width="39px"></asp:TextBox> = <asp:Label ID="Label1" runat="server"></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="calculate" /> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Button1_Click(object sender, EventArgs e) { try { int a = Int32.Parse(TextBox1.Text); int b = Int32.Parse(TextBox2.Text); int res = a / b; Label1.Text = res.ToString(); } catch (Exception ex) { if (TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0) { ex.Data["ExtraInfo"] = " You can't divide " + TextBox1.Text + " by " + TextBox2.Text + "."; } throw ex; } } protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) { if (e.Exception.Data["ExtraInfo"] != null) { ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message + e.Exception.Data["ExtraInfo"].ToString(); } else { ScriptManager1.AsyncPostBackErrorMessage = "An unspecified error occurred."; } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Partial-Page Update Error Handling Example</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:TextBox ID="TextBox1" runat="server" Width="39px"></asp:TextBox> / <asp:TextBox ID="TextBox2" runat="server" Width="39px"></asp:TextBox> = <asp:Label ID="Label1" runat="server"></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="calculate" /> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>
Using Client Script to Customize Error Handling
The previous procedure demonstrated how to customize errors during partial-page rendering by setting properties of the ScriptManager control. The following procedure builds on the customization by using the client PageRequestManager class to display the error message in a <div> element instead of in a browser message box.
To customize error handling in client script
In the page you created earlier, switch to Source view.
Add the following markup to the page:
<div id="AlertDiv"> <div id="AlertMessage"> </div> <br /> <div id="AlertButtons"> <input id="OKButton" type="button" value="OK" runat="server" onclick="ClearErrorState()" /> </div> </div> </div>
<div id="AlertDiv"> <div id="AlertMessage"> </div> <br /> <div id="AlertButtons"> <input id="OKButton" type="button" value="OK" runat="server" onclick="ClearErrorState()" /> </div> </div> </div>
The markup includes elements that you can use to display partial-page rendering errors. It defines a <div> element named AlertDiv that contains two other <div> elements. One of the nested <div> elements contains an <input> control that will enable users to hide the <div> element.
Add the following style markup in the <head> element:
<style type="text/css"> #UpdatePanel1 { width: 200px; height: 50px; border: solid 1px gray; } #AlertDiv{ left: 40%; top: 40%; position: absolute; width: 200px; padding: 12px; border: #000000 1px solid; background-color: white; text-align: left; visibility: hidden; z-index: 99; } #AlertButtons{ position: absolute; right: 5%; bottom: 5%; } </style>
<style type="text/css"> #UpdatePanel1 { width: 200px; height: 50px; border: solid 1px gray; } #AlertDiv{ left: 40%; top: 40%; position: absolute; width: 200px; padding: 12px; border: #000000 1px solid; background-color: white; text-align: left; visibility: hidden; z-index: 99; } #AlertButtons{ position: absolute; right: 5%; bottom: 5%; } </style>
The styles make the error information stand out visually from the rest of the page content.
Switch to Design view and verify that your page resembles the following:
In the drop-down list at the top of the Properties window, select the DOCUMENT element (which represents the <body> element on the page) and set its Id property to bodytag.
Switch to Source view.
Add the following <script> block anywhere after the <asp:ScriptManager> element.
<script type="text/javascript" language="javascript"> var divElem = 'AlertDiv'; var messageElem = 'AlertMessage'; var bodyTag = 'bodytag'; Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function ToggleAlertDiv(visString) { if (visString == 'hidden') { $get(bodyTag).style.backgroundColor = 'white'; } else { $get(bodyTag).style.backgroundColor = 'gray'; } var adiv = $get(divElem); adiv.style.visibility = visString; } function ClearErrorState() { $get(messageElem).innerHTML = ''; ToggleAlertDiv('hidden'); } function EndRequestHandler(sender, args) { if (args.get_error() != undefined) { var errorMessage; if (args.get_response().get_statusCode() == '200') { errorMessage = args.get_error().message; } else { // Error occurred somewhere other than the server page. errorMessage = 'An unspecified error occurred. '; } args.set_errorHandled(true); ToggleAlertDiv('visible'); $get(messageElem).innerHTML = errorMessage; } } </script>
<script type="text/javascript" language="javascript"> var divElem = 'AlertDiv'; var messageElem = 'AlertMessage'; var bodyTag = 'bodytag'; Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function ToggleAlertDiv(visString) { if (visString == 'hidden') { $get(bodyTag).style.backgroundColor = 'white'; } else { $get(bodyTag).style.backgroundColor = 'gray'; } var adiv = $get(divElem); adiv.style.visibility = visString; } function ClearErrorState() { $get(messageElem).innerHTML = ''; ToggleAlertDiv('hidden'); } function EndRequestHandler(sender, args) { if (args.get_error() != undefined) { var errorMessage; if (args.get_response().get_statusCode() == '200') { errorMessage = args.get_error().message; } else { // Error occurred somewhere other than the server page. errorMessage = 'An unspecified error occurred. '; } args.set_errorHandled(true); ToggleAlertDiv('visible'); $get(messageElem).innerHTML = errorMessage; } } </script>
This script does the following:
Defines a handler for the endRequest event of the PageRequestManager class. In the handler, the code displays the AlertDiv <div> element if there is an error condition.
Defines the ToggleAlertDiv function, which hides or shows the AlertDiv element and changes the color of the page based on an error condition.
Defines the ClearErrorState function, which hides the error message UI.
Save your changes and then press CTRL+F5 to view the page in a browser.
Add a number greater than zero to each text box and then click the Calculate button to demonstrate a successful postback.
Change the second text box value to 0 and then click the Calculate button to demonstrate an error condition.
The custom AlertDiv element is displayed instead of the browser message box. The following figure shows an example of the error condition.
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Try Dim a As Int32 a = Int32.Parse(TextBox1.Text) Dim b As Int32 b = Int32.Parse(TextBox2.Text) Dim res As Int32 = a / b Label1.Text = res.ToString() Catch ex As Exception If (TextBox1.Text.Length > 0 AndAlso TextBox2.Text.Length > 0) Then ex.Data("ExtraInfo") = " You can't divide " & _ TextBox1.Text & " by " & TextBox2.Text & "." End If Throw ex End Try End Sub Protected Sub ScriptManager1_AsyncPostBackError(ByVal sender As Object, ByVal e As System.Web.UI.AsyncPostBackErrorEventArgs) If (e.Exception.Data("ExtraInfo") <> Nothing) Then ScriptManager1.AsyncPostBackErrorMessage = _ e.Exception.Message & _ e.Exception.Data("ExtraInfo").ToString() Else ScriptManager1.AsyncPostBackErrorMessage = _ "An unspecified error occurred." End If End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>UpdatePanel Error Handling Example</title> <style type="text/css"> #UpdatePanel1 { width: 200px; height: 50px; border: solid 1px gray; } #AlertDiv{ left: 40%; top: 40%; position: absolute; width: 200px; padding: 12px; border: #000000 1px solid; background-color: white; text-align: left; visibility: hidden; z-index: 99; } #AlertButtons{ position: absolute; right: 5%; bottom: 5%; } </style> </head> <body id="bodytag"> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"> </asp:ScriptManager> <script type="text/javascript" language="javascript"> var divElem = 'AlertDiv'; var messageElem = 'AlertMessage'; var bodyTag = 'bodytag'; Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function ToggleAlertDiv(visString) { if (visString == 'hidden') { $get(bodyTag).style.backgroundColor = 'white'; } else { $get(bodyTag).style.backgroundColor = 'gray'; } var adiv = $get(divElem); adiv.style.visibility = visString; } function ClearErrorState() { $get(messageElem).innerHTML = ''; ToggleAlertDiv('hidden'); } function EndRequestHandler(sender, args) { if (args.get_error() != undefined) { var errorMessage; if (args.get_response().get_statusCode() == '200') { errorMessage = args.get_error().message; } else { // Error occurred somewhere other than the server page. errorMessage = 'An unspecified error occurred. '; } args.set_errorHandled(true); ToggleAlertDiv('visible'); $get(messageElem).innerHTML = errorMessage; } } </script> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:TextBox ID="TextBox1" runat="server" Width="39px"></asp:TextBox> / <asp:TextBox ID="TextBox2" runat="server" Width="39px"></asp:TextBox> = <asp:Label ID="Label1" runat="server"></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="calculate" /> </ContentTemplate> </asp:UpdatePanel> <div id="AlertDiv"> <div id="AlertMessage"> </div> <br /> <div id="AlertButtons"> <input id="OKButton" type="button" value="OK" runat="server" onclick="ClearErrorState()" /> </div> </div> </div> </form> </body> </html>
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Button1_Click(object sender, EventArgs e) { try { int a = Int32.Parse(TextBox1.Text); int b = Int32.Parse(TextBox2.Text); int res = a / b; Label1.Text = res.ToString(); } catch (Exception ex) { if (TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0) { ex.Data["ExtraInfo"] = " You can't divide " + TextBox1.Text + " by " + TextBox2.Text + "."; } throw ex; } } protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) { if (e.Exception.Data["ExtraInfo"] != null) { ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message + e.Exception.Data["ExtraInfo"].ToString(); } else { ScriptManager1.AsyncPostBackErrorMessage = "An unspecified error occurred."; } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>UpdatePanel Error Handling Example</title> <style type="text/css"> #UpdatePanel1 { width: 200px; height: 50px; border: solid 1px gray; } #AlertDiv{ left: 40%; top: 40%; position: absolute; width: 200px; padding: 12px; border: #000000 1px solid; background-color: white; text-align: left; visibility: hidden; z-index: 99; } #AlertButtons{ position: absolute; right: 5%; bottom: 5%; } </style> </head> <body id="bodytag"> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"> </asp:ScriptManager> <script type="text/javascript" language="javascript"> var divElem = 'AlertDiv'; var messageElem = 'AlertMessage'; var bodyTag = 'bodytag'; Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function ToggleAlertDiv(visString) { if (visString == 'hidden') { $get(bodyTag).style.backgroundColor = 'white'; } else { $get(bodyTag).style.backgroundColor = 'gray'; } var adiv = $get(divElem); adiv.style.visibility = visString; } function ClearErrorState() { $get(messageElem).innerHTML = ''; ToggleAlertDiv('hidden'); } function EndRequestHandler(sender, args) { if (args.get_error() != undefined) { var errorMessage; if (args.get_response().get_statusCode() == '200') { errorMessage = args.get_error().message; } else { // Error occurred somewhere other than the server page. errorMessage = 'An unspecified error occurred. '; } args.set_errorHandled(true); ToggleAlertDiv('visible'); $get(messageElem).innerHTML = errorMessage; } } </script> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:TextBox ID="TextBox1" runat="server" Width="39px"></asp:TextBox> / <asp:TextBox ID="TextBox2" runat="server" Width="39px"></asp:TextBox> = <asp:Label ID="Label1" runat="server"></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="calculate" /> </ContentTemplate> </asp:UpdatePanel> <div id="AlertDiv"> <div id="AlertMessage"> </div> <br /> <div id="AlertButtons"> <input id="OKButton" type="button" value="OK" runat="server" onclick="ClearErrorState()" /> </div> </div> </div> </form> </body> </html>
Review
This tutorial showed ways that you can extend error handling during partial-page rendering. In server code you can customize error handling by setting the AsyncPostBackErrorMessage property and handling the AsyncPostBackError event of the ScriptManager control. In client code you can customize error handing by handling the endRequest event of the PageRequestManager class.
See Also
Concepts
Working with PageRequestManager Events