Asp.net回调技术Callback学习笔记(2)
示例3: %@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" % !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/x
示例3:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!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>无标题页</title>
<script type="text/javascript">
//客户端执行的方法
//下面的方法是接收并处理服务器方法返回的结果
function Success(args,context){
message.innerHTML=args;
}
//下面的方式是当接收服务器方法处理的结果发生异常时调用的方法
function Error(){
message.innerHTML="发生了异常!";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
用户名:<input type="text" id="txtUserName" onblur="CallServerMethod(txtUserName.value,null)" />
<span id="message"></span>
<br />
密码:<input type="password" size="10" maxlength="20" id="txtPwd" />
</div>
</form>
</body>
</html>
[code]
public partial class Default3 : System.Web.UI.Page,ICallbackEventHandler //实现ICallbackEventHandler接口
{
String result = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
//获取当前页的ClientScriptManager的引用
ClientScriptManager csm = Page.ClientScript;
/*获取回调的引用.会在客户端生成WebForm_DoCallback方法,
* 调用它来达到异步调用.这个方法是微软写的方法,会被发送
到客户端*/
/*注意这里的"Success"和Error两个字符串分别是客户端代码中
*定义的两个javascript函数*/
//下面的方法最后一个参数的意义:true表示执行异步回调,false标志执行同步回调
String reference = csm.GetCallbackEventReference(this, "args", "Success", "", "Error", true);
String callbackScript = "function CallServerMethod(args,context){\n"+
reference+";\n }";
//向当前页面注册javascript脚本代码
csm.RegisterClientScriptBlock(this.GetType(), "CallServerMethod",callbackScript,true);
}
#region ICallbackEventHandler 成员
/// <summary>
/// 返回回调方法执行结果的方法
/// </summary>
public string GetCallbackResult()
{
return result;
}
/// <summary>
/// 在服务器端运行回调方法
/// </summary>
public void RaiseCallbackEvent(string eventArgument)
{
if (eventArgument.ToLower().IndexOf("admin")!=-1)
{
result =eventArgument+ "不能作为用户注册.";
}
else
{
result = eventArgument + "可以注册.";
}
}
#endregion
}
精彩图集
精彩文章

