次の方法で共有


Partial-Page Rendering Overview

Partial-page rendering removes the need for the whole page to be refreshed as the result of a postback. Instead, only individual regions of the page that have changed are updated. As a result, users do not see the whole page reload with every postback, which makes user interaction with the Web page more seamless. ASP.NET enables you to add partial-page rendering to new or existing ASP.NET Web pages without writing client script.

This topic contains the following sections:

  • Scenarios

  • Features

  • Background

  • Code Examples

  • Class Reference

Scenarios

You can extend existing ASP.NET applications and develop new ones that incorporate AJAX (Asynchronous JavaScript and XML) functionality. Use AJAX features when you want to do the following:

  • Improve the user experience with Web pages that are richer, that are more responsive to user actions, and that behave like traditional client applications.

  • Reduce full-page refreshes and avoid page flicker.

  • Enable cross-browser compatibility without writing client script.

  • Perform AJAX-style client/server communication without writing client script.

  • Use controls and components from the ASP.NET AJAX Control Toolkit.

  • Develop custom ASP.NET AJAX controls.

Partial-Page Rendering Features

Partial-page rendering relies on server controls in ASP.NET and on client functions in the Microsoft AJAX Library. You do not have to use the Microsoft AJAX Library to enable partial-page rendering, because this functionality is provided automatically when you use the ASP.NET AJAX server controls. However, you can use the APIs exposed in the client library for additional AJAX functionality.

The primary features of ASP.NET that support partial-page rendering are:

  • A declarative model that works like ASP.NET server controls. In many scenarios, you can specify partial-page rendering using only declarative markup.

  • Server controls that perform the underlying tasks required for partial-page updates. These include the ScriptManager control and the UpdatePanel control.

  • Integration between ASP.NET AJAX server controls and the Microsoft AJAX Library for common tasks. These tasks include enabling users to cancel a postback, displaying custom progress messages during an asynchronous postback, and determining how concurrent asynchronous postbacks are processed.

  • Error-handling options for partial-page rendering, which enable you to customize how errors are displayed in the browser.

  • Cross-browser compatibility, which is built into the AJAX functionality of ASP.NET. Simply using the server controls automatically invokes the correct browser functionality.

Background

Typical Web pages built with ASP.NET Web server controls perform postbacks initiated by a user action on the page, such as clicking a button. In the response, the server renders a new page. Frequently this re-renders controls and text that did not change between postbacks.

With partial-page rendering, you can refresh individual regions of the page asynchronously and make the page more responsive to the user. You can implement partial-page rendering using ASP.NET AJAX Web server controls, and optionally write client script that uses the APIs in the Microsoft AJAX Library.

Server Controls for Partial-Page Updates

To add AJAX functionality to ASP.NET Web pages, you identify individual sections of the page that you want to update. You then put the content of these sections into UpdatePanel controls. The contents of an UpdatePanel control can be HTML or other ASP.NET controls. You can add an UpdatePanel control to the page as you would any other control. For example, in Visual Studio you can drag it from the toolbox to the Web page, or you can add it by using declarative markup in the page. The following example shows the markup for an UpdatePanel control.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <!-- Place updatable markup and controls here. -->
    </ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <!-- Place updatable markup and controls here. -->
    </ContentTemplate>
</asp:UpdatePanel>

By default, postbacks that originate from controls inside the update panel (child controls) automatically initiate asynchronous postbacks and cause a partial-page update. You can also specify that controls outside the update panel cause an asynchronous postback and that they refresh the UpdatePanel control's content. A control that causes an asynchronous postback is referred to as a trigger. For more information about triggers, see Creating a Simple ASP.NET Page with Multiple UpdatePanel Controls.

An asynchronous postback behaves much like a synchronous postback. All the server page life-cycle events occur, and view state and form data are preserved. However, in the rendering phase, only the contents of the UpdatePanel control are sent to the browser. The rest of the page remains unchanged.

To support partial-page rendering, you must put a ScriptManager control on the page. The ScriptManager control keeps track of all the update panels on the page and of their triggers. It coordinates partial-page rendering behavior on the server, and determines which sections of the page to render as a result of an asynchronous postback.

The following example shows an UpdatePanel control whose content is refreshed whenever a postback originates from inside the panel.

<%@ 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">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Partial-Page Rendering Server-Side Syntax</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:ScriptManager ID="ScriptManager1" runat="server" />
      <asp:UpdatePanel ID="UpdatePanel1" runat="server">
      <ContentTemplate>
        <fieldset>
        <legend>UpdatePanel</legend>
        Content to update incrementally without a full
        page refresh. 
        <br />
        Last update:  <%=DateTime.Now.ToString() %>
        <br />
        <asp:Calendar ID="Calendar" runat="server"/>
        </fieldset>
      </ContentTemplate>
      </asp:UpdatePanel>
      <script type="text/javascript" language="javascript">
      var prm = Sys.WebForms.PageRequestManager.getInstance();
      prm.add_pageLoaded(PageLoadedEventHandler);
      function PageLoadedEventHandler() {
         // custom script
      }
      </script>
    </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">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Partial-Page Rendering Server-Side Syntax</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:ScriptManager ID="ScriptManager1" runat="server" />
      <asp:UpdatePanel ID="UpdatePanel1" runat="server">
      <ContentTemplate>
        <fieldset>
        <legend>UpdatePanel</legend>
        Content to update incrementally without a full
        page refresh. 
        <br />
        Last update:  <%=DateTime.Now.ToString() %>
        <br />
        <asp:Calendar ID="Calendar" runat="server"/>
        </fieldset>
      </ContentTemplate>
      </asp:UpdatePanel>
      <script type="text/javascript" language="javascript">
      var prm = Sys.WebForms.PageRequestManager.getInstance();
      prm.add_pageLoaded(PageLoadedEventHandler);
      function PageLoadedEventHandler() {
         // custom script
      }
      </script>
    </div>
    </form>
</body>
</html>

For more examples of how to use UpdatePanel controls to enable partial-page rendering, see the topics listed in the Code Examples section.

Using Client Script for Partial-Page Updates

The ECMAScript (JavaScript) PageRequestManager class in the Microsoft AJAX Library supports partial-page updates. It runs in the browser to manage the response to asynchronous postbacks and to update content in individual regions. You do not have to do anything to enable this functionality. It occurs automatically when you add one or more UpdatePanel controls and a ScriptManager control to the page.

You can also use JavaScript and the PageRequestManager class to customize partial-page updates on a page. For example, you can write script to give precedence to a specific asynchronous postback if more than one is underway. You can also enable users to cancel postbacks that are in progress.

The following example shows client script that provides an event handler that is called when the page finishes loading.

<script type="text/javascript" language="javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(PageLoadedEventHandler);
function PageLoadedEventHandler() {
   // custom script
}
</script>
<script type="text/javascript" language="javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(PageLoadedEventHandler);
function PageLoadedEventHandler() {
   // custom script
}
</script>

For more information about how to use the Microsoft AJAX Library for partial-page rendering, see Working with PageRequestManager Events and ASP.NET PageRequestManager Class Overview.

Enabling Partial-Page Rendering Support

You enable or disable partial-page rendering for a page by setting the EnablePartialRendering property of the ScriptManager control. You can also specify whether partial-page rendering is supported for a page by setting the SupportsPartialRendering property of the ScriptManager control. If you do not set the SupportsPartialRendering property and if the EnablePartialRendering property is true (which is the default), the capabilities of the browser are used to determine whether partial-page rendering is supported.

If partial-page rendering is not enabled for a page, if it has been disabled, or if it is not supported in a browser, the page uses fallback behavior. Actions that ordinarily would perform an asynchronous postback instead perform a synchronous postback and update the whole page. Any UpdatePanel controls on the page are ignored, and their contents are rendered as if they were not inside an UpdatePanel control.

Note

ASP.NET Web pages that are configured for legacy rendering do not support AJAX functionality. For more information, see ASP.NET and XHTML.

Code Examples

The following example shows partial-page rendering in action. There are two UpdatePanel controls. One control takes user input and another displays a summary of the input.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Collections.Generic" %>

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Enter New Employees</title>
    <script runat="server">
        Private EmployeeList As List(Of Employee)

        Protected Sub Page_Load()
            If Not IsPostBack Then
                EmployeeList = New List(Of Employee)
                EmployeeList.Add(New Employee(1, "Jump", "Dan"))
                EmployeeList.Add(New Employee(2, "Kirwan", "Yvette"))
                ViewState("EmployeeList") = EmployeeList
            Else
                EmployeeList = CType(ViewState("EmployeeList"), List(Of Employee))
            End If

            EmployeesGridView.DataSource = EmployeeList
            EmployeesGridView.DataBind()
        End Sub

        Protected Sub InsertButton_Click(ByVal sender As Object, ByVal e As EventArgs)
            If String.IsNullOrEmpty(FirstNameTextBox.Text) Or _
               String.IsNullOrEmpty(LastNameTextBox.Text) Then Return

            Dim employeeID As Integer = EmployeeList(EmployeeList.Count - 1).EmployeeID + 1

            Dim lastName As String = Server.HtmlEncode(FirstNameTextBox.Text)
            Dim firstName As String = Server.HtmlEncode(LastNameTextBox.Text)

            FirstNameTextBox.Text = String.Empty
            LastNameTextBox.Text = String.Empty

            EmployeeList.Add(New Employee(employeeID, lastName, firstName))
            ViewState("EmployeeList") = EmployeeList

            EmployeesGridView.DataBind()
            EmployeesGridView.PageIndex = EmployeesGridView.PageCount
        End Sub

        Protected Sub CancelButton_Click(ByVal sender As Object, ByVal e As EventArgs)
            FirstNameTextBox.Text = String.Empty
            LastNameTextBox.Text = String.Empty
        End Sub

        <Serializable()> _
        Public Class Employee
            Private _employeeID As Integer
            Private _lastName As String
            Private _firstName As String

            Public ReadOnly Property EmployeeID() As Integer
                Get
                    Return _employeeID
                End Get
            End Property

            Public ReadOnly Property LastName() As String
                Get
                    Return _lastName
                End Get
            End Property

            Public ReadOnly Property FirstName() As String
                Get
                    Return _firstName
                End Get
            End Property

            Public Sub New(ByVal employeeID As Integer, ByVal lastName As String, ByVal firstName As String)
                _employeeID = employeeID
                _lastName = lastName
                _firstName = firstName
            End Sub
        End Class

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;</div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
        <table>
            <tr>
                <td style="height: 206px" valign="top">
                    <asp:UpdatePanel ID="InsertEmployeeUpdatePanel" runat="server" UpdateMode="Conditional">
                        <ContentTemplate>
                          <table cellpadding="2" border="0" style="background-color:#7C6F57">
                            <tr>
                              <td><asp:Label ID="FirstNameLabel" runat="server" AssociatedControlID="FirstNameTextBox" 
                                             Text="First Name" ForeColor="White" /></td>
                              <td><asp:TextBox runat="server" ID="FirstNameTextBox" /></td>
                            </tr>
                            <tr>
                              <td><asp:Label ID="LastNameLabel" runat="server" AssociatedControlID="LastNameTextBox" 
                                             Text="Last Name" ForeColor="White" /></td>
                              <td><asp:TextBox runat="server" ID="LastNameTextBox" /></td>
                            </tr>
                            <tr>
                              <td></td>
                              <td>
                                <asp:LinkButton ID="InsertButton" runat="server" Text="Insert" OnClick="InsertButton_Click" ForeColor="White" />
                                <asp:LinkButton ID="Cancelbutton" runat="server" Text="Cancel" OnClick="CancelButton_Click" ForeColor="White" />
                              </td>
                            </tr>
                          </table>

                          <asp:Label runat="server" ID="InputTimeLabel"><%=DateTime.Now %></asp:Label>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
                <td style="height: 206px" valign="top">
                    <asp:UpdatePanel ID="EmployeesUpdatePanel" runat="server" UpdateMode="Conditional">
                        <ContentTemplate>
                            <asp:GridView ID="EmployeesGridView" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan"
                                BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" AutoGenerateColumns="False">
                                <FooterStyle BackColor="Tan" />
                                <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
                                <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
                                <HeaderStyle BackColor="Tan" Font-Bold="True" />
                                <AlternatingRowStyle BackColor="PaleGoldenrod" />
                                <Columns>
                                    <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" />
                                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                                </Columns>
                                <PagerSettings PageButtonCount="5" />
                            </asp:GridView>
                            <asp:Label runat="server" ID="ListTimeLabel"><%=DateTime.Now %></asp:Label>
                        </ContentTemplate>
                        <Triggers>
                            <asp:AsyncPostBackTrigger ControlID="InsertButton" EventName="Click" />
                        </Triggers>
                    </asp:UpdatePanel>
                </td>
            </tr>
        </table>

    </form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Enter New Employees</title>
    <script runat="server">
        private List<Employee> EmployeeList;

        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                EmployeeList = new List<Employee>();
                EmployeeList.Add(new Employee(1, "Jump", "Dan"));
                EmployeeList.Add(new Employee(2, "Kirwan", "Yvette"));
                ViewState["EmployeeList"] = EmployeeList;
            }
            else
                EmployeeList = (List<Employee>)ViewState["EmployeeList"];

            EmployeesGridView.DataSource = EmployeeList;
            EmployeesGridView.DataBind();
        }

        protected void InsertButton_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(FirstNameTextBox.Text) ||
               String.IsNullOrEmpty(LastNameTextBox.Text)) { return; }

            int employeeID = EmployeeList[EmployeeList.Count-1].EmployeeID + 1;

            string lastName = Server.HtmlEncode(FirstNameTextBox.Text);
            string firstName = Server.HtmlEncode(LastNameTextBox.Text);

            FirstNameTextBox.Text = String.Empty;
            LastNameTextBox.Text = String.Empty;

            EmployeeList.Add(new Employee(employeeID, lastName, firstName));
            ViewState["EmployeeList"] = EmployeeList;

            EmployeesGridView.DataBind();
            EmployeesGridView.PageIndex = EmployeesGridView.PageCount;
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            FirstNameTextBox.Text = String.Empty;
            LastNameTextBox.Text = String.Empty;
        }

        [Serializable]
        public class Employee
        {
            private int _employeeID;
            private string _lastName;
            private string _firstName;

            public int EmployeeID
            {
                get { return _employeeID; }
            }

            public string LastName
            {
                get { return _lastName; }
            }

            public string FirstName
            {
                get { return _firstName; }
            }

            public Employee(int employeeID, string lastName, string firstName)
            {
                _employeeID = employeeID;
                _lastName = lastName;
                _firstName = firstName;
            }
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;</div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
        <table>
            <tr>
                <td style="height: 206px" valign="top">
                    <asp:UpdatePanel ID="InsertEmployeeUpdatePanel" runat="server" UpdateMode="Conditional">
                        <ContentTemplate>
                          <table cellpadding="2" border="0" style="background-color:#7C6F57">
                            <tr>
                              <td><asp:Label ID="FirstNameLabel" runat="server" AssociatedControlID="FirstNameTextBox" 
                                             Text="First Name" ForeColor="White" /></td>
                              <td><asp:TextBox runat="server" ID="FirstNameTextBox" /></td>
                            </tr>
                            <tr>
                              <td><asp:Label ID="LastNameLabel" runat="server" AssociatedControlID="LastNameTextBox" 
                                             Text="Last Name" ForeColor="White" /></td>
                              <td><asp:TextBox runat="server" ID="LastNameTextBox" /></td>
                            </tr>
                            <tr>
                              <td></td>
                              <td>
                                <asp:LinkButton ID="InsertButton" runat="server" Text="Insert" OnClick="InsertButton_Click" ForeColor="White" />
                                <asp:LinkButton ID="Cancelbutton" runat="server" Text="Cancel" OnClick="CancelButton_Click" ForeColor="White" />
                              </td>
                            </tr>
                          </table>

                          <asp:Label runat="server" ID="InputTimeLabel"><%=DateTime.Now %></asp:Label>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
                <td style="height: 206px" valign="top">
                    <asp:UpdatePanel ID="EmployeesUpdatePanel" runat="server" UpdateMode="Conditional">
                        <ContentTemplate>
                            <asp:GridView ID="EmployeesGridView" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan"
                                BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" AutoGenerateColumns="False">
                                <FooterStyle BackColor="Tan" />
                                <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
                                <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
                                <HeaderStyle BackColor="Tan" Font-Bold="True" />
                                <AlternatingRowStyle BackColor="PaleGoldenrod" />
                                <Columns>
                                    <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" />
                                    <asp:BoundField DataField="LastName" HeaderText="Last Name" />
                                    <asp:BoundField DataField="FirstName" HeaderText="First Name" />
                                </Columns>
                                <PagerSettings PageButtonCount="5" />
                            </asp:GridView>
                            <asp:Label runat="server" ID="ListTimeLabel"><%=DateTime.Now %></asp:Label>
                        </ContentTemplate>
                        <Triggers>
                            <asp:AsyncPostBackTrigger ControlID="InsertButton" EventName="Click" />
                        </Triggers>
                    </asp:UpdatePanel>
                </td>
            </tr>
        </table>

    </form>
</body>
</html>

How-to and Walkthrough Topics

Class Reference

The following table lists the key server classes for partial-page rendering.

Class

Description

UpdatePanel

Specifies regions of the page to be updated during partial-page rendering.

ScriptManager

Manages AJAX components in ASP.NET, partial-page rendering, client requests, and server responses on ASP.NET Web pages.

ScriptManagerProxy

Enables nested components to add script and service references to pages that already contain a ScriptManager control in a parent element.

The following table lists the key client class for partial-page rendering.

Class

Description

Sys.WebForms.PageRequestManager Class

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

See Also

Concepts

UpdatePanel Control Overview

ASP.NET PageRequestManager Class Overview