当前位置:首页 > 利用ICallbackEventHandle实现类似AJAX的无刷新页面

利用ICallbackEventHandle实现类似AJAX的无刷新页面

点击次数:1423  更新日期:2010-12-24
\n

先看MSDN Library 2005上的这个例子!
\n

—— ClientCallback.aspx ——
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”ClientCallback.aspx.cs” ­ Inherits=”ClientCallback” %>


\n

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/­ xhtml11.dtd”>


\n

<html xmlns=”http://www.w3.org/1999/xhtm­ l” >
<head id=”Head1″ runat=”server”>
<title>Callback Test</title>
<script type=”text/javascript”>
function ReceiveServerData(receivedStr, context)
{
alert(receivedStr);
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<input type=”button” value=”Callback” onclick=”CallServer(‘argument’, ‘context’)”/><br />
</form>
</body>
</html>


\n

——– ClientCallbacp.aspx.cs ———–


\n


// ClientCallback.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;


\n

public partial class ClientCallback : System.Web.UI.Page, System.Web.UI.ICallbackEventHandle­ r
{


\n

void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this,­ “arg”, “ReceiveServerData”, “”);
String callbackScript = “function CallServer(arg, context) {” + cbReference + “; }”;
cm.RegisterClientScriptBlock(this.­ GetType(), “CallServer”, callbackScript, true);
}


\n

private string returnStr;
//function called by client, executed on server
public void RaiseCallbackEvent(String eventArgument)
{
//do something with return argument
returnStr = eventArgument.ToUpper();
return;
}

//function that sends result?
public string GetCallbackResult()
{
return returnStr;
}
}


\n

客户端用ReceiveServerData接收服务器返回的数据,


\n

<script type=”text/javascript”>
function ReceiveServerData(receivedStr, context)
{
alert(receivedStr);
}
</script>


\n

使用CallServer(‘argument’, ‘context’)传递数据到服务器。


\n

客户端ok了,接下来是服务器端,实现ICallbackEventHandle­ 接口,


\n

private string returnStr;
public void RaiseCallbackEvent(String eventArgument)
{
returnStr = eventArgument.ToUpper();
return;
}

public string GetCallbackResult()
{
return returnStr;
}


\n

最后,将客户端方法和服务器端的方法关联起来,在Page_Load中实现,


\n

ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this,­ “arg”, “ReceiveServerData”, “”);
String callbackScript = “function CallServer(arg, context) {” + cbReference + “; }”;
cm.RegisterClientScriptBlock(this.­ GetType(), “CallServer”, callbackScript, true);


\n

大功告成!


\n

这种方法也能达到类似ajax的无刷新页面,而且实现起来十分简单。


\n
来源:博客园

\n