UpdatePanel 控件概述

更新:2007 年 11 月

使用 ASP.NET UpdatePanel 控件可生成功能丰富的、以客户端为中心的 Web 应用程序。通过使用 UpdatePanel 控件,可以刷新页的选定部分,而不是使用回发刷新整个页面。这称为执行“部分页更新”。包含一个 ScriptManager 控件和一个或多个 UpdatePanel 控件的 ASP.NET 网页可自动参与部分页更新,而不需要自定义客户端脚本。

本主题包含有关以下内容的信息:

  • 方案

  • 背景

  • 代码示例

  • 类参考

方案

UpdatePanel 控件是一个服务器控件,可帮助您开发具有复杂的客户端行为的网页,使网页与最终用户之间具有更强的交互性。若要编写用于在服务器和客户端之间进行协调的代码以仅更新网页的指定部分,通常需要深入了解 ECMAScript (JavaScript)。不过,通过使用 UpdatePanel 控件,可以使网页参与到部分页更新中,而无需编写任何客户端脚本。如果需要,可以添加自定义客户端脚本以增强客户端用户体验。当使用 UpdatePanel 控件时,页行为是独立于浏览器的,并且有可能会减少在客户端和服务器之间传输的数据量。

背景

UpdatePanel 控件通过指定页中无需刷新整个页面即可更新的区域发挥作用。此过程由 ScriptManager 服务器控件和客户端 PageRequestManager 类来协调。当启用部分页更新时,控件可以通过异步方式发布到服务器。异步回发的行为与常规回发类似:生成的服务器页执行完整的页和控件生命周期。不过,通过使用异步回发,可将页更新限制为包含在 UpdatePanel 控件中并标记为要更新的页区域。服务器仅将受影响的元素的 HTML 标记发送到浏览器。在浏览器中,客户端 PageRequestManager 类执行文档对象模型 (DOM) 操作以将现有 HTML 替换为更新的标记。

Bb386454.alert_note(zh-cn,VS.90).gif说明:

使用异步回发或使用 XMLHTTPRequest 对象时,如果 URL 包含双字节字符,则可能发生回发错误。此问题可以通过下面的方法得到解决:在页面的 head 元素中加入 <base href="url"/> 元素,其中 href 属性设置为引用该页面的 URL 编码的字符串。可以添加动态添加到服务器代码中的此元素。

下图演示一个首次加载的页和一个后续异步回发,该回发将刷新 UpdatePanel 控件的内容。

部分页呈现概述
部分页呈现概述

启用部分页更新

UpdatePanel 控件在网页中需要 ScriptManager 控件。默认情况下,将启用部分页更新,因为 ScriptManager 控件的 EnablePartialRendering 属性的默认值为 true。

下面的示例显示用于定义页面上的 ScriptManager 控件和 UpdatePanel 控件的标记。UpdatePanel 控件包含一个 Button 控件,当单击该控件时,将刷新面板中的内容。默认情况下,ChildrenAsTriggers 属性为 true。因此,Button 控件将用作异步回发控件。

<asp:ScriptManager ID="ScriptManager" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
    <ContentTemplate>
       <fieldset>
       <legend>UpdatePanel content</legend>
        <!-- Other content in the panel. -->
        <%=DateTime.Now.ToString() %>
        <br />
        <asp:Button ID="Button1" 
                    Text="Refresh Panel" 
                    runat="server" />
        </fieldset>
    </ContentTemplate>
</asp:UpdatePanel>
<asp:ScriptManager ID="ScriptManager" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
    <ContentTemplate>
       <fieldset>
       <legend>UpdatePanel content</legend>
        <!-- Other content in the panel. -->
        <%=DateTime.Now.ToString() %>
        <br />
        <asp:Button ID="Button1" 
                    Text="Refresh Panel" 
                    runat="server" />
        </fieldset>
    </ContentTemplate>
</asp:UpdatePanel>

指定 UpdatePanel 控件内容

可以通过声明方式向 UpdatePanel 控件添加内容,也可以在设计器中通过使用 ContentTemplate 属性来添加内容。在标记中,将此属性作为 ContentTemplate 元素公开。若要以编程方式添加内容,请使用 ContentTemplateContainer 属性。

当首次呈现包含一个或多个 UpdatePanel 控件的页时,将呈现 UpdatePanel 控件的所有内容并将这些内容发送到浏览器。在后续异步回发中,可能会更新各个 UpdatePanel 控件的内容。更新将与面板设置、导致回发的元素以及特定于每个面板的代码有关。

指定 UpdatePanel 触发器

默认情况下,UpdatePanel 控件内的任何回发控件都将导致异步回发并刷新面板的内容。但是,也可以配置页上的其他控件来刷新 UpdatePanel 控件。可以通过为 UpdatePanel 控件定义触发器来做到这一点。触发器是一类绑定,用于指定使面板更新的回发控件和事件。当引发触发器控件的指定事件(例如,按钮的 Click 事件)时,将刷新更新面板。

下面的示例演示如何为 UpdatePanel 控件指定触发器。

<asp:Button ID="Button1" 
            Text="Refresh Panel"
            runat="server" />
<asp:ScriptManager ID="ScriptManager1" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
                 <Triggers>
                   <asp:AsyncPostBackTrigger ControlID="Button1" />
                 </Triggers>
                 <ContentTemplate>
                 <fieldset>
                 <legend>UpdatePanel content</legend>
                 <%=DateTime.Now.ToString() %>
                 </fieldset>
                 </ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button1" 
            Text="Refresh Panel"
            runat="server" />
<asp:ScriptManager ID="ScriptManager1" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
                 <Triggers>
                   <asp:AsyncPostBackTrigger ControlID="Button1" />
                 </Triggers>
                 <ContentTemplate>
                 <fieldset>
                 <legend>UpdatePanel content</legend>
                 <%=DateTime.Now.ToString() %>
                 </fieldset>
                 </ContentTemplate>
</asp:UpdatePanel>

使用 UpdatePanel 控件的 Triggers 元素内的 asp:AsyncPostBackTrigger 元素定义触发器。(如果在 Visual Studio 中编辑页面,则可以使用**“UpdatePanelTrigger 集合编辑器”**对话框创建触发器。)

触发器的控件事件是可选的。如果不指定事件,则触发器事件是控件的默认事件。例如,对于 Button 控件,默认事件是 Click 事件。

如何刷新 UpdatePanel 控件

下面的列表描述 UpdatePanel 控件的属性设置,这些设置确定在部分页呈现过程中何时刷新面板的内容。

如果 ChildrenAsTriggers 属性设置为 false 且 UpdateMode 属性设置为 Always,则将引发异常。此 ChildrenAsTriggers 属性仅在 UpdateMode 属性设置为 Conditional 时使用。

在母版页中使用 UpdatePanel 控件

若要在母版页中使用 UpdatePanel 控件,必须决定如何包含 ScriptManager 控件。如果在母版页上包含 ScriptManager 控件,则可将其用作所有内容页的 ScriptManager 控件。(如果要以声明方式在内容页中注册脚本或服务,可将 ScriptManagerProxy 控件添加到该内容页。)

如果母版页不包含 ScriptManager 控件,则可以将 ScriptManager 控件单独放置在包含 UpdatePanel 控件的每个内容页上。设计选择取决于您计划如何管理应用程序中的客户端脚本。有关如何管理客户端脚本的更多信息,请参见 ScriptManager 控件概述。有关母版页的更多信息,请参见 ASP.NET 母版页概述

在某些情况下,ScriptManager 控件位于母版页上,对于某个内容页,不需要使用部分页呈现功能。在上述情况下,对于相应的内容页,必须以编程方式将 ScriptManager 控件的 EnablePartialRendering 属性设置为 false。

下面的示例显示用于母版页上的 ScriptManager 控件和内容页上的 UpdatePanel 控件的标记。在本示例中,将在母版页上定义一个名为 LastUpdate 的属性,并从 UpdatePanel 控件内部引用该属性。

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

    Public Property LastUpdate() As DateTime
        Get
            If ViewState("LastUpdate") Is Nothing Then
                Return DateTime.Now
            Else : Return ViewState("LastUpdate")
            End If
        End Get
        Set(ByVal value As DateTime)
            ViewState("LastUpdate") = value
        End Set
    End Property

    Protected Sub MasterButton2_Click(ByVal Sender As Object, ByVal E As EventArgs)
        LastUpdate = DateTime.Now
        Dim up1 As UpdatePanel
        up1 = ContentPlaceHolder1.FindControl("UpdatePanel1")
        up1.Update()

    End Sub
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        ScriptManager1.RegisterAsyncPostBackControl(Button2)
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ScriptManager in Master Page Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:Panel ID="MasterPanel1" runat="server" GroupingText="Master Page">
               <asp:Button ID="Button1" runat="server" Text="Full Page Refresh" />
               <asp:Button ID="Button2" runat="server" Text="Refresh Panel" OnClick="MasterButton2_Click" />
            </asp:Panel>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
    </form>
</body>
</html>
<%@ Master 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">

    public DateTime LastUpdate
    {
        get
        {
            return (DateTime)(ViewState["LastUpdate"] ?? DateTime.Now);
        }
        set
        {
            ViewState["LastUpdate"] = value;
        }
    }


    protected void MasterButton2_Click(object sender, EventArgs e)
    {
        LastUpdate = DateTime.Now;
        ((UpdatePanel)ContentPlaceHolder1.FindControl("UpdatePanel1")).Update();

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager1.RegisterAsyncPostBackControl(Button2);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ScriptManager in Master Page Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:Panel ID="MasterPanel1" runat="server" GroupingText="Master Page">
               <asp:Button ID="Button1" runat="server" Text="Full Page Refresh" />
               <asp:Button ID="Button2" runat="server" Text="Refresh Panel" OnClick="MasterButton2_Click" />
            </asp:Panel>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
    </form>
</body>
</html>
<%@ Page Language="VB" MasterPageFile="MasterVB.master"
    Title="ScriptManager in Content Page" %>

<%@ MasterType VirtualPath="MasterVB.master" %>

<script runat="server">

    Protected Sub Button3_Click(ByVal Sender As Object, ByVal E As EventArgs)
       Master.LastUpdate = DateTime.Now
    End Sub

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
    runat="Server">
    </asp:ScriptManagerProxy>
    <asp:Panel ID="Panel2"
               GroupingText="ContentPage"
               runat="server" >
        <asp:UpdatePanel ID="UpdatePanel1" 
                         UpdateMode="Conditional" 
                         runat="server">
            <ContentTemplate>
                <p>
                    Last updated: <strong>
                        <%= Master.LastUpdate.ToString() %>
                    </strong>
                </p>
                <asp:Button ID="Button3"
                            Text="Refresh Panel"
                            OnClick="Button3_Click"
                            runat="server"  />
            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>
</asp:Content>
<%@ Page Language="C#" MasterPageFile="MasterCS.master"
    Title="ScriptManager in Content Page" %>

<%@ MasterType VirtualPath="MasterCS.master" %>

<script runat="server">

    protected void Button3_Click(object sender, EventArgs e)
    {
        Master.LastUpdate = DateTime.Now;
    }

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
    runat="Server">
    <asp:Panel ID="Panel2"
               GroupingText="ContentPage"
               runat="server" >
        <asp:UpdatePanel ID="UpdatePanel1" 
                         UpdateMode="Conditional" 
                         runat="server">
            <ContentTemplate>
                <p>
                    Last updated: <strong>
                        <%= Master.LastUpdate.ToString() %>
                    </strong>
                </p>
                <asp:Button ID="Button3"
                            Text="Refresh Panel"
                            OnClick="Button3_Click"
                            runat="server"  />
            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>
</asp:Content>

使用嵌套的 UpdatePanel 控件

UpdatePanel 控件可以嵌套。如果刷新父面板,则也会刷新所有嵌套的面板。

下面的示例显示用于在一个 UpdatePanel 控件内定义另一个 UpdatePanel 控件的标记。父面板中的按钮会同时触发父面板和子面板中的内容更新;而子面板中的按钮仅触发子面板的更新。

<%@ 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 id="Head1" runat="server">
    <title>UpdatePanelUpdateMode Example</title>
    <style type="text/css">
    div.NestedPanel
    {
      position: relative;
      margin: 2% 5% 2% 5%;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager" 
                               runat="server" />
            <asp:UpdatePanel ID="OuterPanel" 
                             UpdateMode="Conditional" 
                             runat="server">
                <ContentTemplate>
                    <div>
                        <fieldset>
                            <legend>Outer Panel </legend>
                            <br />
                            <asp:Button ID="OPButton1" 
                                        Text="Outer Panel Button" 
                                        runat="server" />
                            <br />
                            Last updated on
                            <%= DateTime.Now.ToString() %>
                            <br />
                            <br />
                            <asp:UpdatePanel ID="NestedPanel1" 
                                               UpdateMode="Conditional"
                                               runat="server">
                                <ContentTemplate>
                                    <div class="NestedPanel">
                                        <fieldset>
                                            <legend>Nested Panel 1</legend>
                                            <br />
                                            Last updated on
                                            <%= DateTime.Now.ToString() %>
                                            <br />
                                            <asp:Button ID="NPButton1"
                                                        Text="Nested Panel 1 Button" 
                                                        runat="server" />
                                        </fieldset>
                                    </div>
                                </ContentTemplate>
                            </asp:UpdatePanel>
                        </fieldset>
                    </div>
                </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">
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>UpdatePanelUpdateMode Example</title>
    <style type="text/css">
    div.NestedPanel
    {
      position: relative;
      margin: 2% 5% 2% 5%;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager" 
                               runat="server" />
            <asp:UpdatePanel ID="OuterPanel" 
                             UpdateMode="Conditional" 
                             runat="server">
                <ContentTemplate>
                    <div>
                        <fieldset>
                            <legend>Outer Panel </legend>
                            <br />
                            <asp:Button ID="OPButton1" 
                                        Text="Outer Panel Button" 
                                        runat="server" />
                            <br />
                            Last updated on
                            <%= DateTime.Now.ToString() %>
                            <br />
                            <br />
                            <asp:UpdatePanel ID="NestedPanel1" 
                                               UpdateMode="Conditional"
                                               runat="server">
                                <ContentTemplate>
                                    <div class="NestedPanel">
                                        <fieldset>
                                            <legend>Nested Panel 1</legend>
                                            <br />
                                            Last updated on
                                            <%= DateTime.Now.ToString() %>
                                            <br />
                                            <asp:Button ID="NPButton1"
                                                        Text="Nested Panel 1 Button" 
                                                        runat="server" />
                                        </fieldset>
                                    </div>
                                </ContentTemplate>
                            </asp:UpdatePanel>
                        </fieldset>
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

下面的示例演示一个带有 GridView 控件的嵌套的 UpdatePanel 控件。GridView 控件位于 UpdatePanel 控件内,且每个 GridView 行包含嵌套在另一个 UpdatePanel 控件内的 GridView 控件。

<%@ Page Language="VB" %>

<!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>Browse Departments</title>
    <script runat="server">
        Protected Sub DepartmentsGridView_RowDataBound(sender As object, e As GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim s As SqlDataSource = CType(e.Row.FindControl("EmployeesDataSource"), SqlDataSource)
                Dim r As System.Data.DataRowView = CType(e.Row.DataItem, System.Data.DataRowView)
                s.SelectParameters("DepartmentID").DefaultValue = r("DepartmentID").ToString()
            End If
        End Sub
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true" />
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
        <asp:GridView ID="DepartmentsGridView" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" CellPadding="4" DataSourceID="DepartmentDataSource"
            ForeColor="#333333" GridLines="None" PageSize="3" OnRowDataBound="DepartmentsGridView_RowDataBound">
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="GroupName" HeaderText="Division" SortExpression="GroupName" >
                    <ItemStyle Width="200px" />
                </asp:BoundField>
                <asp:BoundField DataField="Name" HeaderText="Department Name" SortExpression="Name" >
                    <ItemStyle Width="160px" />
                </asp:BoundField>
                <asp:TemplateField HeaderText="Employees">
                    <ItemTemplate>
                        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:GridView ID="EmployeesGridView" runat="server" AllowPaging="True" AllowSorting="True"
                                    AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None"
                                    BorderWidth="1px" CellPadding="3" DataSourceID="EmployeesDataSource" GridLines="Vertical"
                                    PageSize="4">
                                    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                                    <Columns>
                                        <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" >
                                            <ItemStyle Width="80px" />
                                        </asp:BoundField>
                                        <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" >
                                            <ItemStyle Width="160px" />
                                        </asp:BoundField>
                                    </Columns>
                                    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                                    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                                    <AlternatingRowStyle BackColor="Gainsboro" />
                                </asp:GridView>
                                <asp:Label runat="server" ID="InnerTimeLabel"><%=DateTime.Now %></asp:Label>
                                <asp:SqlDataSource ID="EmployeesDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
                                    SelectCommand="SELECT HumanResources.EmployeeDepartmentHistory.DepartmentID, 
                                                          HumanResources.vEmployee.EmployeeID, 
                                                          HumanResources.vEmployee.FirstName, 
                                                          HumanResources.vEmployee.LastName 
                                                   FROM HumanResources.EmployeeDepartmentHistory
                                                   INNER JOIN HumanResources.vEmployee 
                                                     ON HumanResources.EmployeeDepartmentHistory.EmployeeID = HumanResources.vEmployee.EmployeeID
                                                   WHERE HumanResources.EmployeeDepartmentHistory.DepartmentID = @DepartmentID
                                                   ORDER BY HumanResources.vEmployee.LastName ASC, HumanResources.vEmployee.FirstName ASC">
                                    <SelectParameters>
                                      <asp:Parameter Name="DepartmentID" DefaultValue="0" Type="int32" />
                                    </SelectParameters>
                                </asp:SqlDataSource>
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </ItemTemplate>
                    <ItemStyle Height="170px" Width="260px" />
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" VerticalAlign="Top" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" VerticalAlign="Top" />
        </asp:GridView>
        <asp:Label runat="server" ID="OuterTimeLabel"><%=DateTime.Now %></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
        &nbsp;
        <asp:SqlDataSource ID="DepartmentDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
            SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department ORDER BY Name">
        </asp:SqlDataSource>

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Browse Departments</title>
    <script runat="server">
        protected void DepartmentsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                SqlDataSource s = (SqlDataSource)e.Row.FindControl("EmployeesDataSource");
                System.Data.DataRowView r = (System.Data.DataRowView)e.Row.DataItem;
                s.SelectParameters["DepartmentID"].DefaultValue = r["DepartmentID"].ToString();
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true" />
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
        <asp:GridView ID="DepartmentsGridView" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" CellPadding="4" DataSourceID="DepartmentDataSource"
            ForeColor="#333333" GridLines="None" PageSize="3" OnRowDataBound="DepartmentsGridView_RowDataBound">
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="GroupName" HeaderText="Division" SortExpression="GroupName" >
                    <ItemStyle Width="200px" />
                </asp:BoundField>
                <asp:BoundField DataField="Name" HeaderText="Department Name" SortExpression="Name" >
                    <ItemStyle Width="160px" />
                </asp:BoundField>
                <asp:TemplateField HeaderText="Employees">
                    <ItemTemplate>
                        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:GridView ID="EmployeesGridView" runat="server" AllowPaging="True" AllowSorting="True"
                                    AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None"
                                    BorderWidth="1px" CellPadding="3" DataSourceID="EmployeesDataSource" GridLines="Vertical"
                                    PageSize="4">
                                    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                                    <Columns>
                                        <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" >
                                            <ItemStyle Width="80px" />
                                        </asp:BoundField>
                                        <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" >
                                            <ItemStyle Width="160px" />
                                        </asp:BoundField>
                                    </Columns>
                                    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                                    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                                    <AlternatingRowStyle BackColor="Gainsboro" />
                                </asp:GridView>
                                <asp:Label runat="server" ID="InnerTimeLabel"><%=DateTime.Now %></asp:Label>
                                <asp:SqlDataSource ID="EmployeesDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
                                    SelectCommand="SELECT HumanResources.EmployeeDepartmentHistory.DepartmentID, 
                                                          HumanResources.vEmployee.EmployeeID, 
                                                          HumanResources.vEmployee.FirstName, 
                                                          HumanResources.vEmployee.LastName 
                                                   FROM HumanResources.EmployeeDepartmentHistory
                                                   INNER JOIN HumanResources.vEmployee 
                                                     ON HumanResources.EmployeeDepartmentHistory.EmployeeID = HumanResources.vEmployee.EmployeeID
                                                   WHERE HumanResources.EmployeeDepartmentHistory.DepartmentID = @DepartmentID
                                                   ORDER BY HumanResources.vEmployee.LastName ASC, HumanResources.vEmployee.FirstName ASC">
                                    <SelectParameters>
                                      <asp:Parameter Name="DepartmentID" DefaultValue="0" Type="int32" />
                                    </SelectParameters>
                                </asp:SqlDataSource>
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </ItemTemplate>
                    <ItemStyle Height="170px" Width="260px" />
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" VerticalAlign="Top" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" VerticalAlign="Top" />
        </asp:GridView>
        <asp:Label runat="server" ID="OuterTimeLabel"><%=DateTime.Now %></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
        &nbsp;
        <asp:SqlDataSource ID="DepartmentDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
            SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department ORDER BY Name">
        </asp:SqlDataSource>

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

当内部 GridView 控件显示一页新记录时,不会刷新外部面板和外部 GridView 控件的其他行中的面板。当外部 GridView 控件显示一页新记录时,外部面板和嵌套的面板都会刷新。

以编程方式刷新 UpdatePanel

下面的示例演示如何以编程方式刷新 UpdatePanel 控件。在本示例中,页通过调用 RegisterAsyncPostBackControl 方法将一个控件注册为触发器。代码通过调用 Update 方法以编程方式刷新 UpdatePanel 控件。

<%@ 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 Property AnsweredQuestions As SortedList
        Get
            If ViewState("AnsweredQuestions") IsNot Nothing Then
                Return CType(ViewState("AnsweredQuestions"), SortedList)
            Else 
                Return New SortedList()
            End If
        End Get
        Set
          ViewState("AnsweredQuestions") = value
        End Set
    End Property

    Protected Sub Page_Load()
        ScriptManager1.RegisterAsyncPostBackControl(SurveyDataList)
    End Sub

    Protected Sub ChoicesRadioButtonList_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim answers As SortedList = Me.AnsweredQuestions
        Dim r As RadioButtonList = CType(sender, RadioButtonList)
        answers(r.ToolTip) = r.SelectedValue
        Me.AnsweredQuestions = answers

        ResultsList.DataSource = Me.AnsweredQuestions
        ResultsList.DataBind()

        If Me.AnsweredQuestions.Count = SurveyDataList.Items.Count Then _
            SubmitButton.Visible = True

        UpdatePanel1.Update()
    End Sub

    Protected Sub SubmitButton_Click(sender As Object, e As EventArgs)
        ' Submit responses.
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Registering Controls as Async Postback Controls</title>
    <style type="text/css">
    .AnswerFloatPanelStyle {
    background-color: bisque;
    position: absolute;
    right: 10px;
    height: 130px;
    width: 150px;
    border-right: silver thin solid; border-top: silver thin solid; 
    border-left: silver thin solid; border-bottom: silver thin solid;    
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <div id="AnswerFloatPanel" class="AnswerFloatPanelStyle" runat="server">
                <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                    <ContentTemplate>
                        Completed Questions:
                        <asp:DataList ID="ResultsList" runat="server">
                            <ItemTemplate>
                                <asp:Label ID="ResultQuestion" runat="server" Text='<%# Eval("Key") %>' />
                                ::
                                <asp:Label ID="ResultAnswer" runat="server" Text='<%# Eval("Value") %>' />
                            </ItemTemplate>
                        </asp:DataList>
                        <p style="text-align: right">
                            <asp:Button ID="SubmitButton" Text="Submit" runat="server" Visible="false"
                                OnClick="SubmitButton_Click" />
                        </p>
                        <asp:Label ID="Message" runat="Server" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>

            <asp:XmlDataSource ID="SurveyDataSource" 
                               runat="server" 
                               XPath="/Questions/Question"
                               DataFile="~/App_Data/SurveyQuestions.xml"/>
            <asp:DataList
                ID="SurveyDataList"
                DataSourceID="SurveyDataSource"
                runat="server">

                <ItemTemplate>
                  <table cellpadding="2" cellspacing="2">
                    <tr>
                      <td valign="top">
                        <asp:Label id="QuestionLabel" Text='<%# XPath("@Title")%>' runat="server" />
                      </td>
                    </tr>
                    <tr><td>
                      <asp:RadioButtonList ID="ChoicesRadioButtonList" runat="server" 
                        DataSource='<%#XPathSelect("Choices/Choice") %>'
                        DataTextField="InnerText" DataValueField="InnerText" 
                        AutoPostBack="True"
                        ToolTip='<%# "Question" + XPath("@ID") %>'
                        OnSelectedIndexChanged="ChoicesRadioButtonList_SelectedIndexChanged"/>
                    </td></tr>
                  </table>
                  <hr />
                </ItemTemplate>
            </asp:DataList>
        </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 SortedList AnsweredQuestions
    {
        get { return (SortedList)(ViewState["AnsweredQuestions"] ?? new SortedList()); }
        set { ViewState["AnsweredQuestions"] = value; }
    }

    protected void Page_Load()
    {
        ScriptManager1.RegisterAsyncPostBackControl(SurveyDataList);
    }

    protected void ChoicesRadioButtonList_SelectedIndexChanged(object sender, EventArgs e)
    {
        SortedList answers = this.AnsweredQuestions;
        RadioButtonList r = (RadioButtonList)sender;
        answers[r.ToolTip] = r.SelectedValue;
        this.AnsweredQuestions = answers;

        ResultsList.DataSource = this.AnsweredQuestions;
        ResultsList.DataBind();

        if (this.AnsweredQuestions.Count == SurveyDataList.Items.Count)
            SubmitButton.Visible = true;

        UpdatePanel1.Update();
    }

    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        // Submit responses.
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Registering Controls as Async Postback Controls</title>
    <style type="text/css">
    .AnswerFloatPanelStyle {
    background-color: bisque;
    position: absolute;
    right: 10px;
    height: 130px;
    width: 150px;
    border-right: silver thin solid; border-top: silver thin solid; 
    border-left: silver thin solid; border-bottom: silver thin solid;    
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <div id="AnswerFloatPanel" class="AnswerFloatPanelStyle" runat="server">
                <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                    <ContentTemplate>
                        Completed Questions:
                        <asp:DataList ID="ResultsList" runat="server">
                            <ItemTemplate>
                                <asp:Label ID="ResultQuestion" runat="server" Text='<%# Eval("Key") %>' />
                                ::
                                <asp:Label ID="ResultAnswer" runat="server" Text='<%# Eval("Value") %>' />
                            </ItemTemplate>
                        </asp:DataList>
                        <p style="text-align: right">
                            <asp:Button ID="SubmitButton" Text="Submit" runat="server" Visible="false"
                                OnClick="SubmitButton_Click" />
                        </p>
                        <asp:Label ID="Message" runat="Server" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>

            <asp:XmlDataSource ID="SurveyDataSource" 
                               runat="server" 
                               XPath="/Questions/Question"
                               DataFile="~/App_Data/SurveyQuestions.xml"/>
            <asp:DataList
                ID="SurveyDataList"
                DataSourceID="SurveyDataSource"
                runat="server">

                <ItemTemplate>
                  <table cellpadding="2" cellspacing="2">
                    <tr>
                      <td valign="top">
                        <asp:Label id="QuestionLabel" Text='<%# XPath("@Title")%>' runat="server" />
                      </td>
                    </tr>
                    <tr><td>
                      <asp:RadioButtonList ID="ChoicesRadioButtonList" runat="server" 
                        DataSource='<%#XPathSelect("Choices/Choice") %>'
                        DataTextField="InnerText" DataValueField="InnerText" 
                        AutoPostBack="True"
                        ToolTip='<%# "Question" + XPath("@ID") %>'
                        OnSelectedIndexChanged="ChoicesRadioButtonList_SelectedIndexChanged"/>
                    </td></tr>
                  </table>
                  <hr />
                </ItemTemplate>
            </asp:DataList>
        </div>
    </form>
</body>
</html>

以编程方式创建 UpdatePanel 控件

若要以编程方式向页中添加 UpdatePanel 控件,请创建 UpdatePanel 控件的新实例。然后,通过使用 ContentTemplateContainer 属性和 ControlCollection.Add 方法向新实例添加控件。不要直接向 ContentTemplate 属性添加控件。

当以编程方式添加 UpdatePanel 控件时,仅来自与 UpdatePanel 控件处于同一命名容器中的控件的回发可用作面板的触发器。

下面的示例演示如何以编程方式向页中添加 UpdatePanel 控件。此示例通过使用 ContentTemplateContainer 属性向面板添加 LabelButton 控件。因为 ChildrenAsTriggers 属性默认为 true,所以 Button 控件用作面板的触发器。

<%@ 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 Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
        Dim up1 As UpdatePanel
        up1 = New UpdatePanel()
        up1.ID = "UpdatePanel1"
        up1.UpdateMode = UpdatePanelUpdateMode.Conditional
        Dim button1 As Button
        button1 = New Button()
        button1.ID = "Button1"
        button1.Text = "Submit"
        AddHandler button1.Click, AddressOf Button_Click
        Dim label1 As Label
        label1 = New Label()
        label1.ID = "Label1"
        label1.Text = "A full page postback occurred."
        up1.ContentTemplateContainer.Controls.Add(button1)
        up1.ContentTemplateContainer.Controls.Add(label1)
        Page.Form.Controls.Add(up1)

    End Sub
    Protected Sub Button_Click(ByVal Sender As Object, ByVal E As EventArgs)
        Dim lbl As Label
        lbl = Page.FindControl("Label1")
        lbl.Text = "Panel refreshed at " & _
            DateTime.Now.ToString()
    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>UpdatePanel Added Programmatically Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="TheScriptManager"
                               runat="server" />
        </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 Page_Load(object sender, EventArgs e)
    {
        UpdatePanel up1 = new UpdatePanel();
        up1.ID = "UpdatePanel1";
        up1.UpdateMode = UpdatePanelUpdateMode.Conditional;
        Button button1 = new Button();
        button1.ID = "Button1";
        button1.Text = "Submit";
        button1.Click += new EventHandler(Button_Click);
        Label label1 = new Label();
        label1.ID = "Label1";
        label1.Text = "A full page postback occurred.";
        up1.ContentTemplateContainer.Controls.Add(button1);
        up1.ContentTemplateContainer.Controls.Add(label1);
        Page.Form.Controls.Add(up1);

    }
    protected void Button_Click(object sender, EventArgs e)
    {
        ((Label)Page.FindControl("Label1")).Text = "Panel refreshed at " +
            DateTime.Now.ToString();
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>UpdatePanel Added Programmatically Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="TheScriptManager"
                               runat="server" />
        </div>
    </form>
</body>
</html>

与 UpdatePanel 控件不兼容的控件

下面的 ASP.NET 控件与部分页更新不兼容,因此不应在 UpdatePanel 控件内使用:

  • 处于多种情况下的 TreeView 控件。一种情况是启用了不是异步回发的一部分的回调。另一种情况是将样式直接设置为控件属性,而不是通过使用对 CSS 样式的引用来隐式设置控件的样式。还有一种情况是 EnableClientScript 属性为 false(默认值为 true)。另外,还有一种情况是在异步回发之间更改了 EnableClientScript 属性的值。有关更多信息,请参见 TreeView Web 服务器控件概述

  • Menu 控件(将样式直接设置为控件属性,而不是通过使用对 CSS 样式的引用来隐式设置控件的样式时)。有关更多信息,请参见 菜单控件概述

  • FileUploadHtmlInputFile 控件(当它们作为异步回发的一部分用于上载文件时)。

  • GridViewDetailsView 控件(当它们的 EnableSortingAndPagingCallbacks 属性设置为 true 时)。默认值为 false。

  • LoginPasswordRecoveryChangePasswordCreateUserWizard 控件(其内容尚未转换为可编辑的模板)。

  • Substitution 控件。

若要在 UpdatePanel 控件内使用 FileUploadHtmlInputFile 控件,请将提交文件的回发控件设置为面板的 PostBackTrigger 控件。仅可以在回发方案中使用 FileUploadHtmlInputFile 控件。

所有其他控件都可以在 UpdatePanel 控件内发挥作用。不过,在某些情况下,控件在 UpdatePanel 控件内可能不会按预期方式工作。这些情况包括:

  • 通过调用 ClientScriptManager 控件的注册方法注册脚本。

  • 在该控件呈现过程中直接呈现脚本或标记,例如,通过调用 Write 方法。

如果该控件调用 ClientScriptManager 控件的脚本注册方法,则也许能够改用 ScriptManager 控件相应的脚本注册方法。在此情况下,该控件可以在 UpdatePanel 控件内工作。

在 UpdatePanel 控件内使用 Web 部件控件

ASP.NET Web 部件是一组集成控件,用于创建网站使最终用户可以直接从浏览器修改网页的内容、外观和行为。可以在 UpdatePanel 控件内使用 Web 部件控件,但具有以下限制:

  • 每个 WebPartZone 控件都必须在同一 UpdatePanel 控件内。例如,页上不能具有两个带有各自的 WebPartZone 控件的 UpdatePanel 控件。

  • WebPartManager 控件管理 Web 部件控件的所有客户端状态信息。它必须在页面上的最外部的 UpdatePanel 控件内。

  • 不能通过使用异步回发导入或导出 Web 部件控件。(执行此任务需要 FileUpload 控件,该控件不能与异步回发一起使用。)默认情况下,导入 Web 部件控件将执行完全回发。

  • 在异步回发过程中,不能添加或修改 Web 部件控件的样式。

有关 Web 部件控件的更多信息,请参见 ASP.NET Web 部件概述

异步回发过程中不支持的属性和方法

在异步回发过程中,不支持在页面上设置默认回发按钮的以下方案:

仅在回发方案(不包括异步回发方案)下才支持 HttpResponse 类的以下方法:

代码示例

下面的部分包含演示如何创建和使用 UpdatePanel 控件的示例。

帮助和演练主题

类参考

下表中显示 UpdatePanel 控件的关键服务器类。

说明

UpdatePanel

一个服务器控件,用于指定可参与部分页更新的网页部分。

ScriptManager

一个服务器控件,用于管理部分页呈现。ScriptManager 控件注册脚本组件以发送到浏览器。它还重写页呈现,以便仅呈现页的指定区域。

ScriptManagerProxy

一个服务器控件,可使嵌套的组件(如内容页或用户控件)能够添加脚本和 Web 服务引用。如果父元素已包含 ScriptManager 控件,则此控件很有用。

PageRequestManager

Microsoft AJAX Library 中的一个类,用于协调浏览器中的部分页呈现。PageRequestManager 类与服务器以异步方式交换信息,并公开用于自定义客户端脚本开发的事件和方法。

其他主题

ASP.NET 页生命周期概述

请参见

任务

UpdatePanel 控件简介

创建具有多个 UpdatePanel 控件的简单 ASP.NET 页

概念

UpdateProgress 控件概述

部分页呈现概述

ASP.NET PageRequestManager 类概述