首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET UpdatePanel 與資料繫結控制項整合實戰指南

     編輯:關於ASP.NET

部分頁面更新:打造流暢的 AJAX 體驗

透過部分頁面呈現(Partial Page Rendering),ASP.NET 應用程式能在無需重新整理整個頁面的情況下,僅更新特定區域,極大提升使用者體驗。這項技術的核心在於 UpdatePanel 與 ScriptManager 兩個伺服器控制項的協作。

核心控制項解析

  • ScriptManager:頁面上僅需一個,負責管理所有 UpdatePanel、追蹤觸發器並協調非同步回發。
  • UpdatePanel:定義可獨立更新的頁面區塊。面板內導致回發的控制項自動成為觸發器;也可透過 Triggers 集合指定面板外部的控制項(甚至是另一個 UpdatePanel 的子控制項)作為觸發條件。

多 UpdatePanel 協作策略

單一頁面可放置任意數量的 UpdatePanel,各自獨立運作。關鍵在於 UpdateMode 屬性的設定:

  • Always(預設):任何部分頁面更新都會觸發此面板重繪。
  • Conditional:僅當面板本身被觸發、或明確呼叫 Update() 方法時才重繪。

善用 Conditional 模式搭配 AsyncPostBackTrigger,可精準控制哪些動作更新哪些區塊,避免不必要的網路傳輸與 UI 閃爍。

完整範例:員工資料輸入與即時顯示

下列範例展示兩個 UpdateMode="Conditional" 的 UpdatePanel 協作:左側為輸入表單,右側為 GridView 顯示清單。點擊「取消」僅清空表單(左側面板更新);點擊「插入」則同時更新表單與清單(兩側面板皆更新)。

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

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <title>新增員工示範</title>
    <script runat="server">
        Private EmployeeList As List(Of Employee)

        Protected Sub Page_Load()
            If Not IsPostBack Then
                EmployeeList = New List(Of Employee) From {
                    New Employee(1, "Jump", "Dan"),
                    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(sender As Object, e As EventArgs)
            If String.IsNullOrEmpty(FirstNameTextBox.Text) OrElse
               String.IsNullOrEmpty(LastNameTextBox.Text) Then Return

            Dim newID = EmployeeList.Last().EmployeeID + 1
            Dim lastName = Server.HtmlEncode(FirstNameTextBox.Text)
            Dim firstName = Server.HtmlEncode(LastNameTextBox.Text)

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

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

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

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

        <Serializable()>
        Public Class Employee
            Public Sub New(id As Integer, ln As String, fn As String)
                _employeeID = id : _lastName = ln : _firstName = fn
            End Sub
            Private _employeeID, _lastName, _firstName
            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
        End Class
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
        <table><tr>
            <td valign="top">
                <asp:UpdatePanel ID="InsertEmployeeUpdatePanel" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <table style="background-color:#7C6F57" cellpadding="2">
                            <tr><td><asp:Label ID="FirstNameLabel" runat="server" AssociatedControlID="FirstNameTextBox" Text="First Name" ForeColor="White" /></td>
                                <td><asp:TextBox ID="FirstNameTextBox" runat="server" /></td></tr>
                            <tr><td><asp:Label ID="LastNameLabel" runat="server" AssociatedControlID="LastNameTextBox" Text="Last Name" ForeColor="White" /></td>
                                <td><asp:TextBox ID="LastNameTextBox" runat="server" /></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 ID="InputTimeLabel" runat="server" Text="<%=DateTime.Now %>" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </td>
            <td valign="top">
                <asp:UpdatePanel ID="EmployeesUpdatePanel" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <asp:GridView ID="EmployeesGridView" runat="server" AutoGenerateColumns="False"
                            BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">
                            <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 ID="ListTimeLabel" runat="server" Text="<%=DateTime.Now %>" />
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="InsertButton" EventName="Click" />
                    </Triggers>
                </asp:UpdatePanel>
            </td>
        </tr></table>
    </form>
</body>
</html>

關鍵技巧總結

  1. 使用 ViewState 保存跨回發的資料集合,避免重複查詢資料庫。
  2. 透過 AsyncPostBackTrigger 明確宣告跨面板觸發關係,語意清晰且易於維護。
  3. 在插入新資料後,將 GridView.PageIndex 設為最後一頁,確保使用者立即看到新增結果。
  4. 兩個面板皆標示 UpdateMode="Conditional",配合觸發器實現精準更新,效能最佳化。

掌握這些模式,即可輕鬆建構出回應迅速、體驗流暢的 ASP.NET AJAX 應用程式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved