ArcIMS.net

using System;
using System.Data;
using System.Configuration;
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ASP.net 2.0 中的客户端回调浅析

Posted on 2006-04-29 12:03  BaobeI  阅读(267)  评论(0)    收藏  举报

ASP.net 2.0之前客户端回调功能地实现方法一般是在jascript 中用XMLHTTP来实现,ASP.net 2.0中增加了客户端回调机制,简单探讨如下:

要想实现客户端回调首先要在Page页面继承ICallbackEventHandler接口,该接口有GetCallbackResult(),RaiseCallbackEvent(string eventArgument)  两个方法 RaiseCallbackEvent用来接收客户端传递的参数,GetCallbackResult则返回处理结果。

基本实现过程:

首先,客户端要激发回调事件,形如:GetSererResult(arg,context){};
方法体由服务器端生成回调事件: ClientScript.GetCallbackEventReference(this, "arg", "GetResult", "context") ,其中arg为由客户端详服务器传递的参数,GetResult为客户端响应服务器端处理结果的方法,(一般有两个参数,形如:GetResult(result,context)。result 是GetCallbackResult()方法返回的结果,context与GetSererResult中context相同)。示例代码如下:

    <script language=Javascript>
        function GetSererResult( arg,context )
        
{
             
<%=ClientScript.GetCallbackEventReference( this"arg""GetResult""context" ) %>;
        }

        
        function GetResult( result,context )
        
{
            alert( result );
        }

    
</script>


服务器端 RaiseCallbackEvent(string eventArgument) eventArgument 接收参数 arg,经过处理由GetCallbackResult(),返回给客户端,这里的参数传递可由Page中的成员变量完成。

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
    
string StrClientArgs;

    
protected void Page_Load(object sender, EventArgs e)
    
{
    }


    
public string GetCallbackResult()
    
{
        
return "Your Args is: " + StrClientArgs;
    }


    
public void RaiseCallbackEvent(string eventArgument)
    
{
        StrClientArgs 
= eventArgument;
    }

}

实现机制:

查看 生成页面源代码,我们可以看到,ClientScript.GetCallbackEventReference( this"arg""GetResult""context" )生成了 WebForm_DoCallback('__Page',obj,GetResult,context,null,false);同时产生了一个包含的js页面 <script src="/net2feature/WebResource.axd?d=mp0YIOta5TA-kuangkJK_Q2&amp;t=632788078083183911" type="text/javascript"></script> 在缓存中找到该页并改为.js文件,可以查看其基本原理,

try {
        xmlRequest 
= new XMLHttpRequest();
    }

    
catch(e) {
        
try {
            xmlRequest 
= new ActiveXObject("Microsoft.XMLHTTP");
        }

        
catch(e) {
        }

    }

callback.xmlRequest = xmlRequest;
        xmlRequest.open(
"POST", theForm.action, true);
        xmlRequest.setRequestHeader(
"Content-Type""application/x-www-form-urlencoded");
        xmlRequest.send(postData);

由此可见,该CallBack由 XMLHttpRequest 实现。