【转】 ASP.NET使用ICallbackEventHandler无刷新验证用户名是否可用

功能说明:当用户在用户名输入框输入字符并焦点离开此输入框时,自动到数据库用户表中验证此用户名是否已被注册,如果已被注册,显示【不可用】,反之,显示【可用】,期间页面不刷新,读者也可以考虑将提示文字换成图片等更佳体验的提示方式。

(只是的个Demo,没有考虑诸如Sql注入等问题,期间参考了网上的个别关于ICallbackEventHandler使用的案例。这个Demo是今天在首页看了某个大虾关于用ICallbackEventHandler无刷新获取服务器时间后做的,文章地址忘了,呵呵~,等找到后补上)。

前台代码:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ver.aspx.cs" Inherits="Ver" %>
<!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 language="javascript">
function VerName() {
//传给后台的参数,在方法RaiseCallbackEvent()中实现
 var message = document.getElementById("txtName").value;
 var context = "";
 <%=sCallBackFunctionInvocation%>;
}
function ShowMessage(Mes, context) {
//Mes 是后台GetCallbackResult()的返回值
var spMes = document.getElementById("spMes");
if(Mes == "true") {
spMes.innerHTML = "可用";
}
else{
spMes.innerHTML = "不可用";
} }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
用户名:<asp:TextBox ID="txtName" runat="server" onblur="VerName()"></asp:TextBox>
<span id="spMes"></span>
<br />
密&nbsp;&nbsp;&nbsp;&nbsp;码:<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
</div>
</form>
</html>

后台代码:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data.Common; public partial class Ver : System.Web.UI.Page,ICallbackEventHandler
{
public string sCallBackFunctionInvocation;
//接收前台传入的值
string userName = ""; void Page_Load(object sender, System.EventArgs e)
{
//注册脚本到前台
sCallBackFunctionInvocation = Page.ClientScript.GetCallbackEventReference(this, "message", "ShowMessage", "context");
} #region ICallbackEventHandler 成员 public string GetCallbackResult()
{
using (SqlConnection conn = new SqlConnection(
System.Configuration.ConfigurationManager.AppSettings["ConnStr"]))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = string.Format(
"Select Count(*) From PUsers Where UserName='{0}'",
userName);
conn.Open();
if (int.Parse(cmd.ExecuteScalar().ToString()) == )
{
return "false";
}
else
{
return "true";
}
}
}
//接收前台参数
public void RaiseCallbackEvent(string eventArgument)
{
userName = eventArgument;
} #endregion
}
上一篇:MySQL查询所有数据库表出错


下一篇:java登陆验证码与JS无刷新验证