ICallbackEventHandler的例子

此事例是从数据库Area表中根据AreaID,无刷新地显示Area。

前台页面显示:btnShowArea的单击事件中调用了GetArea(txtAreaID,lblArea),第一个参数是填写省份ID的TextBox,第二参数是显示省份的Label,两个都是控件。在客户端方法GetArea(areaID,context) 中,先取得txtAreaID内的值赋给areaid,再使用       <%= Page.ClientScript.GetCallbackEventReference(this, "areaid", "Show", "context") %>;调用回调方法,这里面有个参数Show,是一个客户端方法,此方法的第一个参数是字符串,第二个是控件,实现将字符串显示在控件上。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Callback.aspx.cs" Inherits="Test_Callback"
    Theme
="" 
%>

<!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 id="Head1" runat="server">
    
<title>ICallbackEventHandler的例子</title>

    
<script language="javascript" type="text/javascript">
<!--
function Show(area,context)
{
       context.innerHTML
=area;
}

function GetArea(areaID,context) 
{
       areaId
=areaID.value;
       
<%= Page.ClientScript.GetCallbackEventReference(this"areaId""Show""context"%>;
}


// -->
    
</script>

</head>
<body>
    
<h1>
        ICallbackEventHandler的例子
    
</h1>
    
<form id="form1" runat="server">
        
<div>
            
<br />
            
<input id="txtAreaID" type="text" />
            
<input id="btnShowArea" type="button" value="显示省名" onclick="GetArea(txtAreaID,lblArea)" /><br />
            
<asp:Label ID="lblArea" runat="server" Text="请输入省ID"></asp:Label></div>
    
</form>
</body>
</html>

后台代码:声明了一个局部变量Area,用来保存回调返回的值,实现ICallbackEventHandler
接口有两个方法,RaiseCallbackEvent(string eventArgument)为此变量赋值,这里从数据库中找出AreaID对应的Area,赋给Area,而GetCallbackResult()就将此值返回,两个方法,一个实现了回调的方法,另一个返回了回调的结果。

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 Test_Callback : System.Web.UI.Page, ICallbackEventHandler
{
    
private string area;
    
protected void Page_Load(object sender, EventArgs e)
    
{

    }


    
ICallbackEventHandler 成员
}

在做此实例中有几点注意:
1、我原先使用Literal代替Label显示返回的Area,结果不行,这是因为Literal生成的HTML纯粹是字符,而Label生成的HTML则是<span id="lblArea"></span>,这样,客户端方法才能调用这个控件。
2、刚开始我弄很久都不明白,其实最主要的东西在 Page.ClientScript.GetCallbackEventReference(this, "areaid", "Show", "context") 上。这是客户回调方法,里面的参数弄明白就好理解了,ClientScript是System.Web.UI.Page对象的一个属性,它是System.Web.UI.ClientScriptManager对象。用于管理客户端脚本,GetCallbackEventReference方法用于注册一个服务器端事件的客户端回调。它的第四个参数“Context”非常重要,Context被我用于设定一个用来显示服务端返回结果的控件。其实,你可以将任意的对象赋值给Context,它都会被传递给本地端处理回调返回结果的函数,这样,你就可以根据调用前指定的“上下文”灵活的操作返回结果了!
3、在用户控件中用要注意了
<input id="Button2" type="button" value="button" onclick="show(Join1_TextBoxName.value)" />
看看这个加粗的部分,这是运行后查看源代码查到的,Join1是用户控件名,TextBoxName是用户控件中的名字,这里要注意不能直接用TextBoxName,可以运行后通过查看源代码查到,有经验的可以自己猜出控件名来。
原文地址:https://www.cnblogs.com/yvesliao/p/856012.html