1、Client端异步Callback的介绍:它是通过前端Client端向后端服务器传递参数数据,服务器再以接收到的参数进行查询或处理,最后将结果回传给前端显示结果的技术。
2、如果大家AJAX 异步技术比较熟悉的话,那么对Client-Callback技术应该也不会陌生的。Client-Callback技术与AJAX其实实现的效果是一样的,只不过实现的技术与方式不同罢了。她们异步传送与接收少量数据,实现局步刷新,而非Postback整个ViewState状态。这样比起传统的给用户一个不错的体验!
3、上面已经粗略介绍了一下Client-Callback技术,下面我将会举一个例子来阐述一下实现的过程吧。
客户端Callback.aspx页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CallBack.aspx.cs" Inherits="CallBack" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Client端的异步Callback</title>
<script language="javascript" type="text/javascript">
function Sum()
{
var Result=document.getElementById("txtResult");
CallServer(Result.innerText,"");
}
function ReceiveServerData(rvalue)
{
txtResult.innerText=rvalue;
}
window.setInterval("Sum()",1000);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="txtResult">0</div>
</div>
</form>
</body>
</html>
服务器端的Callback.aspx.cs文件:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class CallBack : System.Web.UI.Page,ICallbackEventHandler
{
public int Num = 0;//初始化计数器;
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;//定义一个管理客户端脚本的方法cs
string cbReference = cs.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");//获取一个对ReceiveServerData客户端函数的引用,将启动一个对服务器端事件的客户端回调
string CallBackScript="function CallServer(arg,context){"+cbReference+";}";
cs.RegisterClientScriptBlock(this.GetType(), "CallServer", CallBackScript, true);//动态注册js脚本
}
public void RaiseCallbackEvent(string i)
{
Num = Convert.ToInt32(i) + 1;
}
public string GetCallbackResult()
{
return Num.ToString();//返回计算器
}
}
本人认为实现该技术的有两大重点:
第一、在Page_Load方法中获取ReceiveServerData客户端函数的引用,并进行回调。
第二、从ICallbackEventHandler.cs中的代码来看:
namespace System.Web.UI
{
using System;
using System.Security.Permissions;
using System.Web;
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public interface ICallbackEventHandler
{
string GetCallbackResult();
void RaiseCallbackEvent(string eventArgument);
}
}
页面必须继承IcallbackEventHandler接口,实现该接口需要两种方法:RaiseCallbackEvent()和GetCallbackResult()。要注意的是第一个RaiseCallbackEvent()方法不用返回值的,参数类型只有一个并且是string类型的;而GetCallbackResult()方法要返回string类型值,并且是无参数的。
最后,本人可能分析得不怎么够好,若有什么错或者其他原因请不吝请教。
评论