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