DavidJGu's Blog

       尼采说,宁可追求虚无也不能无所追求!  Keeping is harder than winning
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Difference between ICallbackEventHandler and AJAX

Posted on 2006-09-02 20:42  Let's DotNet  阅读(413)  评论(0编辑  收藏  举报

  作为ASP.NET 2.0 的新特性,ICallbackEventHandler给我们完整的AJAX体验,而且实现/控制更加简单;但事实上ICallbackEventHandler并不是一个完整的AJAX实现,否则也不会有Atlas的开发~

  目前来看,ICallbackEventHandler是一种轻量级的类AJAX实现,优点是不用周折于客户端创建XMLHttpRequest对象时的兼容性问题,而把重点放在局部HttpRequest的处理上;缺点(至少目前是)是向服务端提交数据不太方便,不能是Post方式,只能是一个字符串~

  下面是随意写的一个hello word,

   Page
  
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Hello ICallBackHandler</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
&nbsp;<br />
        
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        
<asp:Button ID="Button1" runat="server" Text="Button" /><br />
        
&nbsp;<br />
        
<br />
        
<br />
        
        
<div style="color:Red" id="ddd"></div>
        
</div>
    
</form>
</body>
</html>

  Code-behind
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 _Default : System.Web.UI.Page,ICallbackEventHandler
{
    
private const string CALLBACK_PARAM = "callbackTest";
    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!Page.IsPostBack)
        
{
            
        }

        
        InitClientResource();
    }


    
private void InitClientResource()
    
{
        
string callBackStartScript = string.Empty;
        
string callBackEndScript = string.Empty;

        callBackStartScript 
= "function callServer(arg,context) {  " + Page.ClientScript.GetCallbackEventReference(this"arg""callEnd""context"+ "; }  \r\nfunction getContext() { return document.getElementById('" + this.TextBox1.ClientID + "').value; } \r\n";
        
        Page.ClientScript.RegisterClientScriptBlock(
this.GetType(), "callServer", callBackStartScript, true);

        callBackEndScript 
= "function callEnd(arg,context) { document.getElementById('ddd').innerText = arg;}";
        Page.ClientScript.RegisterClientScriptBlock(
this.GetType(), "callEnd", callBackEndScript, true);

        Button1.OnClientClick 
= string.Format("callServer({0},'{1}'); return false;","getContext()" ,CALLBACK_PARAM);
    }


    
ICallbackEventHandler Members
}



  Reference:
[1] http://msdn2.microsoft.com/en-us/library/ms178208.aspx;
[2] http://dotnet.sys-con.com/read/121828_p.htm
[3] http://staff.develop.com/ballen/blog/PermaLink.aspx?guid=c35c43f6-5686-40ee-9752-8095a848d821