<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
//客户端执行的方法
//下面的方法是接收并处理服务器方法执行的返回结果
function Success(args, context) {
message.innerText = args;
}
//下面的方式是当接收服务器方法处理的结果发生异常时调用的方法
function Error(args, context) {
message.innerText = "发生了异常";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table border="1" cellpadding="0" cellspacing="0" width="400px">
<tr>
<td width="100px">
用户名
</td>
<td>
<input type="text" size="10" maxlength="20" id="txtUserName" οnblur="CallServerMethod(txtUserName.value,null)" /><span
id="message"></span>
</td>
</tr>
<tr>
<td>
密码
</td>
<td>
<input type="password" size="10" maxlength="20" id="txtPwd" />
</td>
</tr>
</table>
</form>
</body>
</html>
后台:
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
string result = "";
// 定义在服务器端运行的回调方法.
public void RaiseCallbackEvent(String eventArgument)
{
if (eventArgument.ToLower().IndexOf("admin") != -1)
{
result = eventArgument + "不能作为用户名注册。";
}
else
{
result = eventArgument + "可以注册。";
}
// throw new Exception();
}
//定义返回回调方法执行结果的方法
public string GetCallbackResult()
{
return result;
}
//服务器上执行的方法
public 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", false);
String callbackScript = "function CallServerMethod(args, context) {" +
reference + " }";
// 向当前页面注册javascript脚本代码
csm.RegisterClientScriptBlock(this.GetType(), "CallServerMethod",
callbackScript, true);
}
}