使用者控制項(.ascx)同樣能享受 UpdatePanel 帶來的 AJAX 體驗。關鍵在於確保頁面上存在 ScriptManager 且 EnablePartialRendering="true"。ScriptManager 會自動管理頁面直屬或巢狀於使用者控制項內的所有 UpdatePanel。
最簡單的做法:在 .aspx 頁面放置 UpdatePanel,將使用者控制項拖入其 ContentTemplate。當 UpdatePanel 更新時,內含的使用者控制項自然跟著重繪。
這樣可讓使用者控制項「自帶」部分更新能力,封裝性更佳。但宿主頁面必須顯式放置 ScriptManager,否則 UpdatePanel 無法運作。若以程式碼動態載入使用者控制項,建議在控制項 Init 階段檢查 ScriptManager.GetCurrent(Page) 是否存在,若無則動態加入。
當單一頁面包含多個需獨立更新的使用者控制項時,可在使用者控制項程式碼後置(Code-behind)暴露內部 UpdatePanel 的關鍵成員:
UpdateMode 屬性:讓宿主頁面決定更新策略(Always/Conditional)。Update() 方法:允許外部程式碼(如頁面上的按鈕點擊事件)強制刷新該使用者控制項。範例建構一個「主-詳細」頁面:
GridView,支援分頁、排序、選取;將選取的 EmployeeID 存於 ViewState,確保跨分頁/排序仍保持選取狀態。DetailsView 與 SqlDataSource,透過 @SelectedEmployeeID 參數顯示詳細資料。其 UpdatePanel 設為 Conditional,僅在 EmployeeList 選取變更或換頁導致選取項目消失時才更新。<%@ Control Language="VB" AutoEventWireup="true" CodeFile="EmployeeInfo.ascx.vb" Inherits="EmployeeInfo" %>
<asp:UpdatePanel ID="EmployeeInfoUpdatePanel" runat="server">
<ContentTemplate>
<asp:Label ID="LastUpdatedLabel" runat="server" />
<asp:DetailsView ID="EmployeeDetailsView" runat="server" DataSourceID="EmployeeDataSource" AutoGenerateRows="False" ...>
<Fields>
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="EmailAddress" HeaderText="E-mail" />
<asp:BoundField DataField="Phone" HeaderText="Phone" />
<asp:BoundField DataField="HireDate" HeaderText="Hire Date" />
<asp:BoundField DataField="VacationHours" HeaderText="Vacation Hours" />
<asp:BoundField DataField="SickLeaveHours" HeaderText="Sick Leave Hours" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="EmployeeDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
SelectCommand="SELECT ... WHERE HumanResources.Employee.EmployeeID = @SelectedEmployeeID">
<SelectParameters>
<asp:Parameter Name="SelectedEmployeeID" />
</SelectParameters>
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
此架構展示如何將 UpdatePanel 封裝於使用者控制項,並透過最小介面暴露控制權,打造模組化、高效能的 AJAX 網頁元件。