前台代码:
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//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>回调练习</title>
<script type = "text/javascript"language ="javascript" >
function CallServerFunction(Num2)
{
//Arg是传向后台方法RaiseCallbackEvent()的参数,这里将操作符操作数一块传过去
Arg = Num2.value;
//获取一个客户端函数的引用;调用该函数时,将启动一个对服务器端事件的客户端回调
<%=ClientScript.GetCallbackEventReference(this,"Arg","ReceiveServerData","null")%>
}
//接收回调后台传过来的结果数据,该函数名为GetCallbackEventReference()的第三个参数
function ReceiveServerData(result)
{
//js里面,必须用Label的innerText属性,用Text属性不会产生任何效果
lblShow.innerText = result;
}
</script>
</head>
<body>
<form id="form1"runat="server">
<div>
<input type = "text"id="Num2" onblur ="CallServerFunction(Num2)"/>
<%--调用回调函数的控件必须是HTML控件,不能为服务端控件--%>
<input type = "text"id="Text1" />
<asp:Label ID="lblShow" runat="server"Text="show"></asp:Label>
</div>
</form>
</body>
</html>
--------------------------------------------------------------------------------------------------
后台代码:
using System;
using System.Data;
using System.Configuration;
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;
using System.Data.SqlClient;
//必须声明System.Web.UI.ICallbackEventHandler接口
public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
//定义一个回调的返回值
privatestring result;
protectedvoid Page_Load(object sender, EventArgs e)
{
}
///<summary>
///该方法是回调执行的方法,根据参数在这个方法中处理回调的内容,该方法没有返回值
///</summary>
///<paramname="eventArgument">此参数是从客户端传过来的</param>
public voidRaiseCallbackEvent(string eventArgument)
{
SqlConnectionStringBuilder conBuilder = newSqlConnectionStringBuilder();
conBuilder.DataSource = "(local)";
conBuilder.InitialCatalog = "pubs";
conBuilder.IntegratedSecurity = true; //Windows身份验证就是true,帐号和密码的就是false
conBuilder.UserID = "false";
conBuilder.Password = "false";
string conStr = conBuilder.ToString();
SqlConnection connect = new SqlConnection(conStr);
connect.Open();
Boolean judge = true;
SqlCommand command = new SqlCommand("select * from Table_1;",connect);
SqlDataReader read =command.ExecuteReader(CommandBehavior.CloseConnection);
while (read.Read())
{
if (eventArgument == read.GetString(0))
{
judge = false;
break;
}
else
judge = true;
}
if (judge == false)
{
result = eventArgument + "该用户不能被注册!";