使用ICallbackEventHandler实现无刷新回调
在ASP.NET 2.0中,引入了一个称为"客户端回调"的功能,利用这个内建的解决方案我们可以轻松实现客户端脚本和服务器端代码间的交互,从而避免了页面因回发带来的频繁刷新。客户端回调本质上就是指通过前端的客户端脚本向服务器端传递相应的数据参数,服务器端再以接受到的参数进行查询和处理,最后将结果回传到客户端进行显示。在网上已经有蛮多实现无刷新回调的文章,之前在ASP.NET1.0 用AJAX技术实现过,现在ASP.NET2.0使用ICallbackEventHandler来实现。具体如下:
前台页面:
<
body
>
<
form
id
="form1"
runat
="server"
>
<
div
>
<
input
id
="txtMessage"
style
="width: 353px"
type
="text"
/>
<
input
id
="Button1"
type
="button"
value
="Call to Server"
onclick
="CallServer();"
/>
<
br
/>
result:
<
input
id
="txtResult"
style
="width: 442px"
type
="text"
/></
div
>
</
form
>
</
body
>
前台脚本:
<
script type
=
"
text/javascript
"
>
function
CallServer()

{
var product = document.getElementById("txtMessage").value;//前台数据传到后台处理
//返回后台处理后的数据到前台,用前台函数ReceiveServerData来接收
<%= ClientScript.GetCallbackEventReference(this, "product", "ReceiveServerData",null)%>;
}
function
ReceiveServerData(rValue)

{
//alert(rValue);
document.getElementById("txtResult").value = rValue;
}
</
script
>
后台代码:
public
partial
class
testNoRefresh : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler

{
protected void Page_Load(object sender, EventArgs e)

{

}

//定义一个字符串,回调的结果信息将保存在该字符串中
private string CallBackValue = string.Empty;


//引发回调事件处理
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)

{
this.CallBackValue = "客户端在[" + DateTime.Now.ToString() + "]传送来 [" + eventArgument + "]!";
}

//回传回调结果
string ICallbackEventHandler.GetCallbackResult()

{
return CallBackValue;
}
}
前台页面:









前台脚本:



















后台代码:































