使用ICallbackEventHandler可以实现简单的异步回调,
我进行了简单的封装,使用方法如下
客户端:
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title></title>
- <script language="javascript" type="text/javascript">
- // <!CDATA[
- function Button1_onclick() {
- CallSrvFun("a", "Test2", myfun);
- }
- function myfun(d) {
- alert("d=" + d);
- }
- // ]]>
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <input id="Password1" type="password" /><input id="Button1" type="button" value="button" onclick="return Button1_onclick()" /></div>
- </form>
- </body>
- </html>
调用方法: CallSrvFun(数据,服务端函数,回调函数)
服务端后台:
- public partial class WebForm2 : HahaPage
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- public void Test1(string data)
- {
- __LJEventValue = "abc1:" + data;
- }
- }
后台要继承自HahaPage类,然后可以写一系列方法供客户端使用
核心在代码hahaPage代码如下:
- public class HahaPage : Page, ICallbackEventHandler
- {
- #region ICallbackEventHandler 成员
- public string __LJEventValue="";
- protected override void OnLoad(EventArgs e)
- {
- base.OnLoad(e);
- string cbre = Page.ClientScript.GetCallbackEventReference(this, "arg", "__LJEventCallBackSrv", "");
- string callback = "function __LJEventCallPageBackSrv(arg){" + cbre + ";}";
- Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "__LJEventCallSrv", callback, true);
- StringBuilder sb = new StringBuilder();
- sb.AppendLine(" var ljcallbackfunction = null;");
- sb.AppendLine("function CallSrvFun(data, event, callbackFunction) {");
- sb.AppendLine(" AddField(/"LjEvent/", event);");
- sb.AppendLine(" __LJEventCallPageBackSrv(data);");
- sb.AppendLine(" ljcallbackfunction = callbackFunction;");
- sb.AppendLine("}");
- sb.AppendLine("function __LJEventCallBackSrv(x) {");
- sb.AppendLine(" eval(/"ljcallbackfunction(x);/");");
- sb.AppendLine("}");
- sb.AppendLine("function AddField(name, value) {");
- sb.AppendLine(" name = WebForm_EncodeCallback(name);");
- sb.AppendLine(" value = WebForm_EncodeCallback(value);");
- sb.AppendLine(" var n = __theFormPostData.indexOf(name);");
- sb.AppendLine(" if (n == -1) { __theFormPostData += name + /"=/" + value + /"&/"; return; }");
- sb.AppendLine(" var m = __theFormPostData.indexOf(/"&/", n);");
- sb.AppendLine(" var left = __theFormPostData.substr(0, n);");
- sb.AppendLine(" var right = __theFormPostData.substr(m);");
- sb.AppendLine(" __theFormPostData = left + name + /"=/" + value + /"&/" + right;");
- sb.AppendLine("}");
- this.Page.ClientScript.RegisterStartupScript(GetType(), "__LJEventInit", sb.ToString(), true);
- }
- public string GetCallbackResult()
- {
- return __LJEventValue;
- }
- public void RaiseCallbackEvent(string eventArgument)
- {
- string eventName = Request["LjEvent"];
- MethodInfo m = this.GetType().GetMethod(eventName);
- if (m == null)
- __LJEventValue = eventArgument;
- else
- m.Invoke(this, new object[] { eventArgument });
- }
- #endregion
- }
Page_Load初始化注册客户端函数
RaiseCallbackEvent 获取回调的函数然后通过反射进行调用!
代码下载:lijun7788.download.csdn.net/