萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 2.0 伺服器控制項開發:實作 IPostBackDataHandler 處理回傳資料與事件

前言

開發自訂伺服器控制項時,若需接收使用者輸入的回傳值 (如 TextBox、DropDownList),必須實作 `IPostBackDataHandler` 介面,參與 ASP.NET 回傳資料處理管線。本文完整說明介面契約、生命週期時機、載入/比對/引發事件流程,並提供可直接使用的自訂文字框控制項範例。

一、回傳資料處理管線流程

  1. 瀏覽器送出表單 (POST),包含所有 `` 的鍵值對。
  2. ASP.NET 執行 `Page.LoadPostData`:遍歷所有實作 `IPostBackDataHandler` 的控制項,比對 `UniqueID` 找到對應的表單欄位值。
  3. 呼叫控制項 `LoadPostData(postDataKey, postCollection)`:
    • 取得舊值 (通常儲存在 `ViewState`)。
    • 取得新值 `postCollection[postDataKey]`。
    • 比較:若不同 → 更新內部狀態、回傳 `true`;若相同 → 回傳 `false`。
  4. 若 `LoadPostData` 回傳 `true`,頁面稍後在 `LoadComplete` 階段呼叫 `RaisePostDataChangedEvent()`。
  5. 控制項在 `RaisePostDataChangedEvent` 中引發語意事件 (如 `TextChanged`),供頁面訂閱處理。

二、IPostBackDataHandler 介面定義

namespace System.Web.UI
{
    public interface IPostBackDataHandler
    {
        // 載入回傳資料,回傳 true 表示資料已變更
        bool LoadPostData(string postDataKey, NameValueCollection postCollection);

        // 引發資料變更事件
        void RaisePostDataChangedEvent();
    }
}

三、完整自訂文字框控制項範例

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:CustomTextBox runat=server></{0}:CustomTextBox>")]
    public class CustomTextBox : WebControl, IPostBackDataHandler
    {
        // === 1. Text 屬性儲存在 ViewState ===
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get => (string)(ViewState["Text"] ?? String.Empty);
            set => ViewState["Text"] = value;
        }

        // === 2. 渲染輸入元素,name 必須等於 UniqueID ===
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");
            writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
            writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID); // 關鍵!
            writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
            if (!string.IsNullOrEmpty(CssClass)) writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass);
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();
        }

        // === 3. 實作 IPostBackDataHandler ===
        bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            string postedValue = postCollection[postDataKey];
            string currentValue = Text;

            // 比較新舊值 (忽略大小寫視需求)
            if (!string.Equals(currentValue, postedValue, StringComparison.Ordinal))
            {
                Text = postedValue ?? String.Empty;
                return true; // 資料已變更,稍後引發 TextChanged
            }
            return false;
        }

        void IPostBackDataHandler.RaisePostDataChangedEvent()
        {
            OnTextChanged(EventArgs.Empty);
        }

        // === 4. 事件定義 (標準 EventHandler 模式) ===
        private static readonly object EventTextChanged = new object();

        [Category("Action")]
        [Description("文字內容變更時觸發")]
        public event EventHandler TextChanged
        {
            add => Events.AddHandler(EventTextChanged, value);
            remove => Events.RemoveHandler(EventTextChanged, value);
        }

        protected virtual void OnTextChanged(EventArgs e)
        {
            EventHandler handler = (EventHandler)Events[EventTextChanged];
            handler?.Invoke(this, e);
        }
    }
}

四、頁面使用範例

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="cc" Namespace="CustomControls" Assembly="CustomControls" %>
<!DOCTYPE html>
<html><body>
<form id="form1" runat="server">
    <cc:CustomTextBox ID="txtInput" runat="server" OnTextChanged="txtInput_TextChanged" AutoPostBack="true" />
    <br />
    <asp:Label ID="lblEcho" runat="server" />
</form></body></html>
public partial class _Default : System.Web.UI.Page
{
    protected void txtInput_TextChanged(object sender, EventArgs e)
    {
        lblEcho.Text = $"您輸入:{txtInput.Text} (於 {DateTime.Now:HH:mm:ss} 觸發 TextChanged)";
    }
}

五、關鍵實作細節與常見錯誤

項目正確做法常見錯誤
渲染 name 屬性`writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);`用 `ClientID` 或寫死字串,導致找不到回傳值
ViewState 儲存舊值`ViewState["Text"]`用私有欄位,回傳後遺失
LoadPostData 回傳值值改變 → `true`;未改變 → `false`永遠回傳 `true` 導致每次都觸發事件
事件引發時機在 `RaisePostDataChangedEvent` 中呼叫 `OnTextChanged`直接在 `LoadPostData` 引發,順序錯誤
AutoPostBack控制項需支援 `AutoPostBack` 屬性並在渲染時輸出 `onchange=\"__doPostBack(...)\"`忘記輸出 `__doPostBack`,使用者離開欄位不回發

六、支援 AutoPostBack 的渲染擴充

[DefaultValue(false)]
public bool AutoPostBack
{
    get => (bool)(ViewState["AutoPostBack"] ?? false);
    set => ViewState["AutoPostBack"] = value;
}

protected override void RenderContents(HtmlTextWriter writer)
{
    writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");
    writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
    writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
    writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);

    if (AutoPostBack)
    {
        // 產生 onchange 觸發回發的腳本
        string postBackRef = Page.ClientScript.GetPostBackEventReference(this, String.Empty);
        writer.AddAttribute(HtmlTextWriterAttribute.Onchange, postBackRef + ";\"); // 注意分號
    }
    writer.RenderBeginTag(HtmlTextWriterTag.Input);
    writer.RenderEndTag();
}

七、進階:實作 IPostBackEventHandler (處理按鈕式回發)

若控制項包含按鈕、連結等觸發回發但不傳遞資料值,需另行實作 `IPostBackEventHandler`:

public class CustomButton : WebControl, IPostBackEventHandler
{
    public event EventHandler Click;

    protected override void RenderContents(HtmlTextWriter writer)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Type, "button");
        writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
        writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
        string postBack = Page.ClientScript.GetPostBackEventReference(this, String.Empty);
        writer.AddAttribute(HtmlTextWriterAttribute.Onclick, postBack);
        writer.RenderBeginTag(HtmlTextWriterTag.Input);
        writer.RenderEndTag();
    }

    void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
    {
        OnClick(EventArgs.Empty);
    }

    protected virtual void OnClick(EventArgs e) => Click?.Invoke(this, e);
}

八、總結

  • 需接收使用者輸入值 → 實作 `IPostBackDataHandler` (TextBox、DropDownList、CheckBox 等)。
  • 需處理點擊/命令回發 → 實作 `IPostBackEventHandler` (Button、LinkButton、ImageButton 等)。
  • 複合控制項可同時實作兩介面。
  • 永遠用 `UniqueID` 做 `name`,用 `ClientID` 做 `id`。
  • 事件模式遵循 `EventHandlerList` + 靜態唯讀物件鍵,確保記憶體效率與序列化正確。
copyright © 萬盛學電腦網 all rights reserved