回調允許控件或頁以不需要回發整個頁的方式執行對伺服器的帶外回調。這意味着您的自定義控件将不會導緻用戶端浏覽器等待整個頁的回發,并且自定義控件能夠啟用豐富的 UI 功能。您可開發自定義控件,輕松組合如 Web 資源及用戶端腳本管理,以使用回調基礎結構。若要啟用回調,您需要:
在自定義控件中建立一個具有給定簽名的伺服器端回調事件 (<code>ICallbackEventHandler.PrepareCallbackEvent</code>),它在有參數傳入方法時起作用。應調用開發人員在擴充您的自定義控件時可重寫的方法;
建立生成回調結果的伺服器端方法 <code>ICallbackEventHandler.RenderCallbackResult</code>。應調用開發人員在擴充您的自定義控件時可重寫的方法。傳回結果将傳遞給由您的自定義控件定義的用戶端腳本;
建立管理傳回調用或錯誤的用戶端腳本。這将通過您的自定義控件生成;
在您的自定義控件中使用與用戶端事件挂鈎的回調事件引用。
C#
public class CustomControl : CompositeControl, ICallbackEventHandler {
void ICallbackEventHandler.PrepareCallbackEvent(string eventArgument) {
PrepareCallBackEvent(eventArgument);
}
String ICallbackEventHandler.RenderCallbackResult() {
return RenderCallbackResult();
private String _callbackEventArg;
// Do work in a protected virtual methods so that derived controls can override
protected virtual void PrepareCallBackEvent(string eventArgument) {
_callbackEventArg = eventArgument;
protected virtual String RenderCallbackResult() {
if (_callbackEventArg == "theArg")
return = "Some data";
return "Only theArg allowed!";
// Additional implementation
// Client script functions that handle the callback
private String sButtonCallBack =
"function ButtonCallBack(result, context) { alert(result); }";
private String sButtonCallBackError =
"function ButtonErrorCallBack(result, context) { alert(result); }";
protected override void OnInit(EventArgs e) {
base.OnInit(e);
// Additional implementation
Page.ClientScript.RegisterClientScriptBlock(typeof(CustomControl),
"ButtonCallBack", sButtonCallBack, true);
"ButtonCallBackError", sButtonCallBackError, true);
protected override void OnPreRender(EventArgs e) {
// Set up the OnClick event to fire an out-of band call to the handler
Attributes["OnClick"] = Page.ClientScript.GetCallbackEventReference(this,
"'theArg'", "ButtonCallback", "null", "ButtonErrorCallback", true);
base.OnPreRender(e);
}
本文轉自永春部落格園部落格,原文連結:http://www.cnblogs.com/firstyi/archive/2006/11/13/559052.html,如需轉載請自行聯系原作者