前台部分:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>回调页面</title>
    <script type="text/javascript">
    function GetResult(result)
    {
        document.forms[0].TextBox1.value=result;   
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" value="执行" onclick="TestCallback(this.form.TextBox1.value);" />
        <asp:TextBox ID="TextBox1" runat="server" Text="ASP.Net文本框控件"></asp:TextBox>
    </div>
    </form>
</body>
</html>

后台:

..............部分省略........

    public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
    {
        private string _callbackResult = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            string cbRef = Page.ClientScript.GetCallbackEventReference(this, "val", "GetResult", null);
            string cbScript = "function TestCallback(val){" + cbRef + ";}";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "TestCallback", cbScript, true);
        }
        public void RaiseCallbackEvent(string evtArg)
        {
            _callbackResult = "#"+evtArg+"#";
        }
        public string GetCallbackResult()
        {
            return _callbackResult;
        }
    }

 

简单的功能,就是对文本框的内容后台做了处理,加上了"#"括了起来,不回传整个页面。

有点像RPC,脚本发起请求,然后回调,页面实现了System.Web.UI.ICallbackEventHandler的2个方法

RaiseCallbackEvent和GetCallbackResult。

整个过程是:

当点击“执行”按钮后,执行

TestCallback(this.form.TextBox1.value);脚本,参数值是文本框的内容,这里默认是"ASP.Net文本框控件",

此参数会发送,然后看下public void RaiseCallbackEvent(string evtArg),他的形参就是客户端发来的数据,这里就是"ASP.Net文本框控件",_callbackResult = "#"+evtArg+"#";处理的数据保存到实例变量里,接着调用

public string GetCallbackResult(),返回该值,实际中返回的并不一定是同一个(比如这里的_callbackResult),比如说客户端发来的是个用户id号,可以读数据库返回个用户名等等。

结果返回给客户端,执行回调函数

    function GetResult(result)
    {
        document.forms[0].TextBox1.value=result;   
    }

他的参数就是服务端的响应结果,这里是“#ASP.Net文本框控件#“,接着函数体内可以根据结果参数执行相应的操作。

 

备注:

附上msdn的一段。

 

public string GetCallbackEventReference(
	Control control,
	string argument,
	string clientCallback,
	string context
)
Visual C++
public:
String^ GetCallbackEventReference(
	Control^ control, 
	String^ argument, 
	String^ clientCallback, 
	String^ context
)
J#
public String GetCallbackEventReference(
	Control control,
	String argument,
	String clientCallback,
	String context
)
JScript
public function GetCallbackEventReference(
	control : Control, 
	argument : String, 
	clientCallback : String, 
	context : String
) : String

参数

control
类型:System.Web.UI..::.Control

处理客户端回调的服务器 Control。该控件必须实现 ICallbackEventHandler 接口并提供 RaiseCallbackEvent 方法。

argument
类型:System..::.String

从客户端脚本传递给服务器的一个参数

RaiseCallbackEvent 方法。

clientCallback
类型:System..::.String

一个客户端事件处理程序的名称,该处理程序接收成功的服务器事件的结果。

context
类型:System..::.String

启动回调之前在客户端计算的客户端脚本。脚本的结果传回客户端事件处理程序。

返回值

类型:System..::.String

调用客户端回调的客户端函数的名称。