Documentation for: ASP.NET Ajax Version 1.0

This documentation is for a previous version. For the current released version, see the ASP.NET Ajax documentation on MSDN.

 

 

 

 

 

 

 

Skip Navigation Links.
Tutorials
Sample ASP.NET AJAX Application
ASP.NET AJAX and JavaScript
Extending JavaScript with ASP.NET AJAX
Creating Custom Client Script in ASP.NET AJAX
Dynamically Assigning ASP.NET AJAX Script References
Globalizing a Date by Using Client Script
Embedding a JavaScript File as a Resource in an Assembly
Embedding Localized Resources for a JavaScript File
Adding Localized Resources to a JavaScript File
Creating Custom Client Events
The UpdatePanel Control
Introduction to the UpdatePanel Control
Creating a Simple ASP.NET Page with Multiple UpdatePanel Controls
Using the UpdatePanel Control with Data-Bound Controls
Using the UpdatePanel Control with Master Pages
Using the UpdatePanel Control with User Controls
Using the UpdatePanel Control with a Web Service
Customizing Error Handling for UpdatePanel Controls
Animating UpdatePanel Controls
Canceling an Asynchronous Postback
Giving Precedence to a Specific Asynchronous Postback
Working with PageRequestManager Events
The UpdateProgress Control
Introduction to the UpdateProgress Control
Programming UpdateProgress Controls in Client Script
The Timer Control
Introduction to the Timer Control
Using the Timer Control with Multiple UpdatePanel Controls
ASP.NET Application Services
Using Forms Authentication
Using Profile Information
Web Services
Exposing Web Services to Client Script
Calling Web Services from Client Script
ASP.NET AJAX Extensibility
Creating Custom ASP.NET AJAX Non-Visual Client Components
Creating Custom ASP.NET AJAX Client Controls
Creating an Extender Control
Adding Client Capabilities to a Web Server Control
Creating a Client Component Class Using the Prototype Model
Defining Custom Component Properties and Raising PropertyChanged Events
Releasing Component Resources

Customizing Error Handling for ASP.NET UpdatePanel Controls

Introduction

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 what information the message contains.

You can see the code in action in this tutorial by clicking the Run It buttons. To implement the procedures in your own development environment you need:

  • Microsoft Visual Studio 2005 or Microsoft Visual Web Developer Express Edition.

  • The latest release of Microsoft ASP.NET AJAX installed and configured. For more information, see Installing ASP.NET AJAX.

  • An ASP.NET AJAX Web site.

To customize error handling in server code

  1. Create a new page and switch to Design view.

  2. In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control and the UpdatePanel control to add them to the page.

    UpdatePanel Tutorial
  3. Add the following controls inside the UpdatePanel control:

    UpdatePanel Tutorial
  4. Double-click the Calculate button and add the following code for its event handler:

    CS

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

    VB

    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
    
    

    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.

  5. Switch to Design view and select the ScriptManager control.

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

    UpdatePanel Tutorial
  7. Add the following code to the AsyncPostBackError event handler:

    CS

    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.";
        }
    }
    
    

    VB

    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
    
    

    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.

  8. Save your changes and then press CTRL+F5 to view the page in a browser.

  9. Add a number greater than zero to each text box and then click the Calculate button to demonstrate a successful postback.

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

    UpdatePanel Tutorial
    note

    The style of the message box depends on what browser you are using, but the message is the same in all browsers.

    To see the full example in action, click the Run It button.

Using Client Script to Customize Error Handling

The preceding 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

  1. In the page you created earlier, switch to Source view.

  2. Add the following markup to the page:

    CS

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

    VB

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

  3. Add the following style markup in the <head> element:

    CS

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

    VB

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

  4. Switch to Design view and verify that your page resembles the following:

    UpdatePanel Tutorial
  5. 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.

    UpdatePanel Tutorial
  6. Switch to Source view.

  7. Add the following <script> block anywhere after the <asp:ScriptManager> element.

    CS

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

    VB

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

  8. Save your changes and then press CTRL+F5 to view the page in a browser.

  9. Add a number greater than zero to each text box and then click the Calculate button to demonstrate a successful postback.

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

    UpdatePanel Tutorial

    To see the full example in action, click the Run It button.

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.