Share via


Managing Partial-Page Updates in Client Script

The PageRequestManager class in the Microsoft Ajax Library manages partial-page updates in the browser. When a page contains a ScriptManager control and one or more UpdatePanel controls, the page is automatically enabled for partial-page rendering. The PageRequestManager class exposes properties, methods, and events that enable you to customize partial-page updates with client script. The PageRequestManager class exposes a client page event model that you can use in a way similar to how you use the server page event model.

This topic contains:

  • Scenarios

  • Features

  • Background

  • Code Examples

  • How-to and Walkthrough Topics

  • Class Reference

Scenarios

You can enable partial-page updates by using the ScriptManager and UpdatePanel Web server controls. Partial-page updates require no client scripting. However, you can use the PageRequestManager class and client script when you want to do the following:

  • Control how multiple asynchronous postbacks are processed. The default behavior is that the last postback takes precedence. The PageRequestManager class enables you to give precedence to a specific postback and cancel others that are underway.

  • Provide visual cues or other notification to mark regions on the page that have been updated or created as a result of the last asynchronous postback. This can improve the user experience, especially in scenarios where multiple UpdatePanel controls are used.

  • Display status messages during asynchronous postbacks. If postbacks take a long time to process, you might want to show a progress indicator such as an animated image. You can also give the user the option to cancel the postback.

  • Provide custom error-message handling for partial-page updates. If an unexpected error occurs during an asynchronous postback, you can handle the error in client script.

  • Access the underlying request and response objects that are used for the asynchronous postback.

Features

Features of partial-page updates in the Microsoft Ajax Library include the following:

  • Client page life-cycle events that are raised at key times during partial-page updates.

  • Information about which UpdatePanel controls were deleted, updated, or created during an asynchronous postback.

  • Properties and methods that enable you to determine in client script whether the page is processing an asynchronous postback. You can also use these methods to stop an asynchronous postback that is underway or to cancel new postbacks.

  • Information about server data that is sent to controls that are not participating in partial-page updates.

Background

During partial-page updates initiated by asynchronous postbacks, the PageRequestManager class coordinates how the page content is incrementally updated in the browser. The UpdatePanel server control and PageRequestManager client class abstract much of the complexity of partial-page updates. When you use client script and members of the PageRequestManager class, you can customize the partial-page update behavior in the browser.

Partial-Page Update Event Handling

During page processing of both postbacks and asynchronous postbacks, you can handle browser document object model (DOM) events to run custom script. For example, you can run script when the browser loads or unloads the page.

However, these DOM events do not enable you to access all relevant information or to control the behavior during asynchronous postbacks and during partial-page updates. Therefore, the PageRequestManager class exposes the following events that enable you to customize partial-page updates:

For more information about these events, see Working with Partial-Page Rendering Events.

Code Examples

The following example shows how to use the pageLoaded event of the PageRequestManager class to animate an UpdatePanel control when the page is updated after an asynchronous postback. In this example, users can select a date and enter an e-mail address into a form to make a ticket request. When an asynchronous postback occurs (triggered by links outside the UpdatePanel control), the panel is animated briefly to notify the user that the date value was entered into the text box. The page contains a pop-up window that displays a Calendar control. The calendar is displayed or hidden using the control's Visible property. The whole page does not have to be refreshed when the calendar is displayed or hidden, or when a date is selected, because the Calendar control is inside an UpdatePanel control.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Protected Sub ChosenDate_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim dt As New DateTime()
        DateTime.TryParse(ChosenDate.Text, dt)

        CalendarPicker.SelectedDate = dt
        CalendarPicker.VisibleDate = dt

    End Sub
    Protected Sub Close_Click(ByVal sender As Object, ByVal e As EventArgs)
        SetDateSelectionAndVisible()        
    End Sub

    Protected Sub ShowDatePickerPopOut_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
        DatePickerPopOut.Visible = Not (DatePickerPopOut.Visible)

    End Sub

    Protected Sub CalendarPicker_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
        SetDateSelectionAndVisible()        
    End Sub

    Private Sub SetDateSelectionAndVisible()
        If (CalendarPicker.SelectedDates.Count <> 0) Then
            ChosenDate.Text = CalendarPicker.SelectedDate.ToShortDateString()
        End If
        DatePickerPopOut.Visible = False
    End Sub

    Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        If (Page.IsValid) Then
            MessageLabel.Text = "An email with availability was sent."
        Else
            MessageLabel.Text = ""
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        CompareValidatorDate.ValueToCompare = DateTime.Today.ToShortDateString()
        ExtraShow1.Text = DateTime.Today.AddDays(10.0).ToShortDateString()
        ExtraShow2.Text = DateTime.Today.AddDays(11.0).ToShortDateString()
    End Sub


    Protected Sub ExtraShow_Click(ByVal sender As Object, ByVal e As EventArgs)
        ChosenDate.Text = CType(sender, LinkButton).Text        
    End Sub

</script>

<html xmlns="https://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Calendar Example</title>
    <style type="text/css">
        body {
            font-family: Tahoma;
        }
        .PopUpCalendarStyle
        {
              background-color:lightblue;
              position:absolute;
              visibility:show;
              margin: 15px 0px 0px 10px;
              z-index:99;   
              border: solid 2px black;
        }
        .UpdatePanelContainer
        {
            width: 260px;
            height:110px;
        }

    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <script type="text/javascript">
        Type.registerNamespace("ScriptLibrary");
        ScriptLibrary.BorderAnimation = function(color, duration) {
            this._color = color;
            this._duration = duration;
        }
        ScriptLibrary.BorderAnimation.prototype = {
            animatePanel: function(panelElement) {
                var s = panelElement.style;
                s.borderWidth = '1px';
                s.borderColor = this._color;
                s.borderStyle = 'solid';
                window.setTimeout(
                    function() {{ s.borderWidth = 0; }},
                    this._duration
                );
            }
        }
        ScriptLibrary.BorderAnimation.registerClass('ScriptLibrary.BorderAnimation', null);

        var panelUpdatedAnimation = new ScriptLibrary.BorderAnimation('blue', 1000);
        var postbackElement;
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);

        function beginRequest(sender, args) {
            postbackElement = args.get_postBackElement();
        }
        function pageLoaded(sender, args) {
            var updatedPanels = args.get_panelsUpdated();
            if (typeof(postbackElement) === "undefined") {
                return;
            } 
            else if (postbackElement.id.toLowerCase().indexOf('extrashow') > -1) {
                for (i=0; i < updatedPanels.length; i++) {            
                    panelUpdatedAnimation.animatePanel(updatedPanels[i]);
                }
            }

        }
        </script>
        <h1>Tickets</h1>
        <p>
            <strong>Latest News</strong> Due to overwhelming response, we
            have added two extra shows on:
            <asp:LinkButton ID="ExtraShow1" runat="server" OnClick="ExtraShow_Click" />
            and
            <asp:LinkButton ID="ExtraShow2" runat="server" OnClick="ExtraShow_Click" />.
            Don't forget curtain time is at 7:00pm sharp. No late arrivals.
        </p>
        <hr />
        <div class="UpdatePanelContainer">
            <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow1" />
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow2" />
                </Triggers>
                <ContentTemplate>
                    <fieldset >
                        <legend>Check Ticket Availability</legend>Date
                        <asp:TextBox runat="server" ID="ChosenDate" OnTextChanged="ChosenDate_TextChanged" />
                        <asp:ImageButton runat="server" ID="ShowDatePickerPopOut" OnClick="ShowDatePickerPopOut_Click"
                            ImageUrl="../images/calendar.gif" AlternateText="Choose a date."
                            Height="20px" Width="20px" />
                        <asp:Panel ID="DatePickerPopOut" CssClass="PopUpCalendarStyle"
                            Visible="false" runat="server">
                            <asp:Calendar ID="CalendarPicker" runat="server" OnSelectionChanged="CalendarPicker_SelectionChanged">
                            </asp:Calendar>
                            <br />
                            <asp:LinkButton ID="CloseDatePickerPopOut" runat="server" Font-Size="small"
                                OnClick="Close_Click" ToolTip="Close Pop out">
                            Close
                            </asp:LinkButton>
                        </asp:Panel>
                        <br />
                        Email
                        <asp:TextBox runat="server" ID="EmailTextBox" />
                        <br />
                        <br />
                        <asp:Button ID="SubmitButton" Text="Check" runat="server" ValidationGroup="RequiredFields"
                            OnClick="SubmitButton_Click" />
                        <br />
                        <asp:CompareValidator ID="CompareValidatorDate" runat="server"
                            ControlToValidate="ChosenDate" ErrorMessage="Choose a date in the future."
                            Operator="GreaterThanEqual" Type="Date" Display="None" ValidationGroup="RequiredFields" EnableClientScript="False"></asp:CompareValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorDate" runat="server"
                            ControlToValidate="ChosenDate" Display="None" ErrorMessage="Date is required."
                            ValidationGroup="RequiredFields" EnableClientScript="False"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
                            runat="server" ControlToValidate="EmailTextBox" Display="None"
                            ValidationGroup="RequiredFields" ErrorMessage="The email was not correctly formatted."
                            ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$" EnableClientScript="False"></asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
                            runat="server" ValidationGroup="RequiredFields" ControlToValidate="EmailTextBox"
                            Display="None" ErrorMessage="Email is required." EnableClientScript="False"></asp:RequiredFieldValidator><br />
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                            ValidationGroup="RequiredFields" EnableClientScript="False" />
                        <asp:Label ID="MessageLabel" runat="server" />
                    </fieldset>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void ChosenDate_TextChanged(object sender, EventArgs e)
    {
        DateTime dt = new DateTime();
        DateTime.TryParse(ChosenDate.Text, out dt);

        CalendarPicker.SelectedDate = dt;
        CalendarPicker.VisibleDate = dt;
    }
    protected void Close_Click(object sender, EventArgs e)
    {
        SetDateSelectionAndVisible();
    }

    protected void ShowDatePickerPopOut_Click(object sender, ImageClickEventArgs e)
    {
        DatePickerPopOut.Visible = !DatePickerPopOut.Visible;
    }

    protected void CalendarPicker_SelectionChanged(object sender, EventArgs e)
    {
        SetDateSelectionAndVisible();
    }

    private void SetDateSelectionAndVisible()
    {
        if (CalendarPicker.SelectedDates.Count != 0)
            ChosenDate.Text = CalendarPicker.SelectedDate.ToShortDateString();
        DatePickerPopOut.Visible = false;
    }

    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            MessageLabel.Text = "An email with availability was sent.";
        }
        else
        {
            MessageLabel.Text = "";
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        CompareValidatorDate.ValueToCompare = DateTime.Today.ToShortDateString();
        ExtraShow1.Text = DateTime.Today.AddDays(10.0).ToShortDateString();
        ExtraShow2.Text = DateTime.Today.AddDays(11.0).ToShortDateString();
    }

    protected void ExtraShow_Click(object sender, EventArgs e)
    {
        ChosenDate.Text = ((LinkButton)sender).Text;
    }
</script>

<html xmlns="https://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Calendar Example</title>
    <style type="text/css">
        body {
            font-family: Tahoma;
        }
        .PopUpCalendarStyle
        {
              background-color:lightblue;
              position:absolute;
              visibility:show;
              margin: 15px 0px 0px 10px;
              z-index:99;   
              border: solid 2px black;
        }
        .UpdatePanelContainer
        {
            width: 260px;
            height:110px;
        }

    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <script type="text/javascript">
        Type.registerNamespace("ScriptLibrary");
        ScriptLibrary.BorderAnimation = function(color, duration) {
            this._color = color;
            this._duration = duration;
        }
        ScriptLibrary.BorderAnimation.prototype = {
            animatePanel: function(panelElement) {
                var s = panelElement.style;
                s.borderWidth = '1px';
                s.borderColor = this._color;
                s.borderStyle = 'solid';
                window.setTimeout(
                    function() {{ s.borderWidth = 0; }},
                    this._duration
                );
            }
        }
        ScriptLibrary.BorderAnimation.registerClass('ScriptLibrary.BorderAnimation', null);

        var panelUpdatedAnimation = new ScriptLibrary.BorderAnimation('blue', 1000);
        var postbackElement;
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);

        function beginRequest(sender, args) {
            postbackElement = args.get_postBackElement();
        }
        function pageLoaded(sender, args) {
            var updatedPanels = args.get_panelsUpdated();
            if (typeof(postbackElement) === "undefined") {
                return;
            } 
            else if (postbackElement.id.toLowerCase().indexOf('extrashow') > -1) {
                for (i=0; i < updatedPanels.length; i++) {            
                    panelUpdatedAnimation.animatePanel(updatedPanels[i]);
                }
            }

        }
        </script>
        <h1>Tickets</h1>
        <p>
            <strong>Latest News</strong> Due to overwhelming response, we
            have added two extra shows on:
            <asp:LinkButton ID="ExtraShow1" runat="server" OnClick="ExtraShow_Click" />
            and
            <asp:LinkButton ID="ExtraShow2" runat="server" OnClick="ExtraShow_Click" />.
            Don't forget curtain time is at 7:00pm sharp. No late arrivals.
        </p>
        <hr />
        <div class="UpdatePanelContainer">
            <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow1" />
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow2" />
                </Triggers>
                <ContentTemplate>
                    <fieldset>
                        <legend>Check Ticket Availability</legend>Date
                        <asp:TextBox runat="server" ID="ChosenDate" OnTextChanged="ChosenDate_TextChanged" />
                        <asp:ImageButton runat="server" ID="ShowDatePickerPopOut" OnClick="ShowDatePickerPopOut_Click"
                            ImageUrl="../images/calendar.gif" AlternateText="Choose a date."
                            Height="20px" Width="20px" />
                        <asp:Panel ID="DatePickerPopOut" CssClass="PopUpCalendarStyle"
                            Visible="false" runat="server">
                            <asp:Calendar ID="CalendarPicker" runat="server" OnSelectionChanged="CalendarPicker_SelectionChanged">
                            </asp:Calendar>
                            <br />
                            <asp:LinkButton ID="CloseDatePickerPopOut" runat="server" Font-Size="small"
                                OnClick="Close_Click" ToolTip="Close Pop out">
                            Close
                            </asp:LinkButton>
                        </asp:Panel>
                        <br />
                        Email
                        <asp:TextBox runat="server" ID="EmailTextBox" />
                        <br />
                        <br />
                        <asp:Button ID="SubmitButton" Text="Check" runat="server" ValidationGroup="RequiredFields"
                            OnClick="SubmitButton_Click" />
                        <br />
                        <asp:CompareValidator ID="CompareValidatorDate" runat="server"
                            ControlToValidate="ChosenDate" ErrorMessage="Choose a date in the future."
                            Operator="GreaterThanEqual" Type="Date" Display="None" ValidationGroup="RequiredFields" EnableClientScript="False"></asp:CompareValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorDate" runat="server"
                            ControlToValidate="ChosenDate" Display="None" ErrorMessage="Date is required."
                            ValidationGroup="RequiredFields" EnableClientScript="False"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
                            runat="server" ControlToValidate="EmailTextBox" Display="None"
                            ValidationGroup="RequiredFields" ErrorMessage="The email was not correctly formatted."
                            ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$" EnableClientScript="False"></asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
                            runat="server" ValidationGroup="RequiredFields" ControlToValidate="EmailTextBox"
                            Display="None" ErrorMessage="Email is required." EnableClientScript="False"></asp:RequiredFieldValidator><br />
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                            ValidationGroup="RequiredFields" EnableClientScript="False" />
                        <asp:Label ID="MessageLabel" runat="server" />
                    </fieldset>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

How-to and Walkthrough Topics

Class Reference

The following table lists the classes that relate to the PageRequestManager class.

Class

Description

Sys.WebForms.PageRequestManager Class

Manages client partial-page updates and exposes members for custom client scripting.

Sys.WebForms.InitializeRequestEventArgs Class

Provides event data for the initializeRequest event, which is raised before the asynchronous request starts.

Sys.WebForms.BeginRequestEventArgs Class

Provides event data for the beginRequest event, which is raised after an asynchronous postback starts and before the postback is sent to the server.

Sys.WebForms.PageLoadingEventArgs Class

Provides event data for the pageLoading event, which is raised after the response to an asynchronous postback is received, but before any content on the page is updated. This event is not raised if the postback is stopped or if an unhandled exception is thrown on the server during processing.

Sys.WebForms.PageLoadedEventArgs Class

Provides event data for the pageLoaded event, which is raised after all content on the page is refreshed, whether as the result of a synchronous postback or an asynchronous postback. This event is not raised if the postback is stopped or if an unhandled exception is thrown on the server during processing.

Sys.WebForms.EndRequestEventArgs Class

Provides event data for the endRequest event, which is raised after an asynchronous postback has finished.

See Also

Concepts

UpdatePanel Control Overview

Managing Partial-Page Updates in Client Script