首先,建立页面基类,服务端必须继承自ICallbackEventHandler接口,代码如下:
public class PageBase : System.Web.UI.Page, ICallbackEventHandler {
protected event PageCallBackEventHandler Page_CallBackEvent;
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
}
protected override void CreateChildControls() {
base.CreateChildControls();
//注册客户端调用的js
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type='text/javascript'>");
sb.Append("function CallBack_Event(Key, context) {");
//定义回调的js方法名CallBackResult
string strCallBack = ClientScript.GetCallbackEventReference(this, "Key", "CallBackResult", "context");
sb.Append(strCallBack);
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("}");
sb.Append("</script>");
RegisterScript(base.GetType(), "InitCallBack" + this.ClientID, sb.ToString());
}
//注册脚本方法
public static void RegisterScript(Type type, string key, string script) {
if ((!string.IsNullOrEmpty(script) && !string.IsNullOrEmpty(key)) && (type != null)) {
string str = type.ToString(); Page currentHandler = HttpContext.Current.CurrentHandler as Page; if (currentHandler != null) {
for (int i = 0; i < currentHandler.Header.Controls.Count; i++) { Control control = currentHandler.Header.Controls[i]; if (control.GetType() == typeof(System.Web.UI.WebControls.ContentPlaceHolder)) { System.Web.UI.WebControls.ContentPlaceHolder cph = control as System.Web.UI.WebControls.ContentPlaceHolder; if (cph != null) { HtmlGenericControl autoCompleteScript = new HtmlGenericControl(); autoCompleteScript.InnerHtml = script; cph.Controls.AddAt(0, autoCompleteScript); break; }
} } } } }
//定义事件委托
protected delegate void PageCallBackEventHandler(object sender, PageCallBackEventArgs e);
//返回值变量
public string ResultData { get; set; }
//定义事件参数
protected class PageCallBackEventArgs : EventArgs { public PageCallBackEventArgs(string str) { this.ClientParameter = str; } public readonly string ClientParameter;
}
//事件处理
protected void OnPageCallBack(PageCallBackEventArgs e)
{
if (Page_CallBackEvent != null)
{
Page_CallBackEvent(this, e);
}
}
//返回值到客户端
public string GetCallbackResult() { return ResultData; }
//接收参数并触发事件
public void RaiseCallbackEvent(string eventArgument) {
PageCallBackEventArgs pcbe = new PageCallBackEventArgs(eventArgument);
OnPageCallBack(pcbe);
}
}
下面是子页面,继承自刚定义的PageBase类,绑定自定义的事件
public partial class _Default : PageBase { protected void Page_Load(object sender, EventArgs e) {
this.Page_CallBackEvent += _Default_Page_CallBackEvent; }
void _Default_Page_CallBackEvent(object sender, PageBase.PageCallBackEventArgs e) { if (e.ClientParameter == "aaa") { this.ResultData = "ccc"; } }
}
接下来是子页面前台
<script type="text/javascript">
function TestClick() {
//触发后台回调
CallBack_Event("aaa", "bbb");
} function CallBackResult(context, result) {
//后台事件返回时会调用此方法
alert(context + "," + result);
} </script>
然后触发TestClick事件,异步回调就出来了。