回调允许控件或页以不需要回发整个页的方式执行对服务器的带外回调。这意味着您的自定义控件将不会导致客户端浏览器等待整个页的回发,并且自定义控件能够启用丰富的 UI 功能。您可开发自定义控件,轻松组合如 Web 资源及客户端脚本管理,以使用回调基础结构。若要启用回调,您需要:
- 在自定义控件中创建一个具有给定签名的服务器端回调事件 (
ICallbackEventHandler.PrepareCallbackEvent
),它在有参数传入方法时起作用。应调用开发人员在扩展您的自定义控件时可重写的方法; - 创建生成回调结果的服务器端方法
ICallbackEventHandler.RenderCallbackResult
。应调用开发人员在扩展您的自定义控件时可重写的方法。返回结果将传递给由您的自定义控件定义的客户端脚本; - 创建管理返回调用或错误的客户端脚本。这将通过您的自定义控件生成;
- 在您的自定义控件中使用与客户端事件挂钩的回调事件引用。
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);
Page.ClientScript.RegisterClientScriptBlock(typeof(CustomControl),
"ButtonCallBackError", sButtonCallBackError, true);
}
// Additional implementation
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,如需转载请自行联系原作者