当前位置:编程学习 > C#/ASP.NET >>

ASP.NET2.0实现无刷新客户端回调(1)

答案:     ASP.net2.0的客户端回调是一种很让人激动的方法,他能够让我们控制要提交什么数据给服务器而不用提交整个页面,同时服务器也只返回你所需要的数据而不要发回整个页面。
  
    首先我们要说一个很重要的方法:GetCallbackEventRefernce.我把我的理解写出来,可能是错误的,恳请指出,非常感谢!
  
    GetCallbackEventReference首先实现让客户端脚本有能力传递参数给服务器端的RaiseCallbackEvent方法,然后返回RaiseCallBackEvent方法的值给你在GetCallbackEventRefernce方法中注册的一个参数(其实也是一个你要在客户端写的脚本)。调用GetCallbackEventRefernce你必须从客户端脚本中传递给他两个参数,一个是要传递给RaiseCallbackEvent事件的值,一个是context.
  
    他的参数意义如下:
  
    第一个:实现了ICallbackEventHandler借口的页面或者服务器控件,写this代表但前页面。
  
    第二个:代表你从要从客户端传递给服务器RaiseCallbackEvent方法的值
  
    第三个:你要在客户端写的一个js函数,同时,服务器也会把计算得到的数据传递给这个函数做为这个函数的参数。
  
    第四个:context具体什么意思我也不太清楚GetCallbackEventRefernce发送到了客户、端的代码是这样的:
  
  WebForm_DoCallback('__Page',arg,ReceiveServerData,context,null,false)
  
    那么我们要怎么样做才能够从客户端调用他呢?看到了三中方法:
  
    第一种:在后台写个public string,在Page_Load中给他赋值为:=Page.ClientScript.GetCallbackEventReference(this, "message", "ShowServerTime", "context");注意在这里是Page.ClientScrip,因为他会返回个ClientScriptManager,ClientScriptManager管理所有的客户端脚本。然后在前台某个按钮的onclick事件里<%=那个public后台字符串%>.做个小实验代码如下:
  
    前台ServerTime.aspx:为了方便去掉好多没用的html
  
  <%@ page language="C#" CodeFile="ServerTime.aspx.cs" Inherits="ServerTime_aspx" %>
  <html>
  <head>
  <title>Server Time</title>
  <script language="javascript">
  
  function GetServerTime()
  {
   var message = '';
   var context = '';
   <%=sCallBackFunctionInvocation%>
  }
  
  function ShowServerTime(timeMessage, context) {
   alert('现在服务器上的时间是:\n' + timeMessage);
  }
  </script>
  </head>
  <body>
  <form id="MainForm" runat="server">
  <input type="button" value="得到服务器端时间" onclick="GetServerTime();" />
  </form>
  </body>
  </html>
  
    后台:
  
  using System;
  using System.Web.UI;
  
  public partial class ServerTime_aspx : Page,ICallbackEventHandler
  {
   //一定要实现ICallbackEventHandler借口
   public string sCallBackFunctionInvocation;
  
   void Page_Load(object sender, System.EventArgs e)
   {
    sCallBackFunctionInvocation = Page.ClientScript.GetCallbackEventReference(this, "message", "ShowServerTime", "context");
   }
  
   public string RaiseCallbackEvent(string eventArgument)
   {
    return DateTime.Now.ToString();
   }
  }
  
    运行,点按钮结果如下:
  
  

上一个:ASP.NET2.0实现无刷新客户端回调(2)
下一个:漫谈ASP.NET设计中的性能优化问题(2)

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,