【转】Ajax 在ASP.Net(C#)中即时验证用户名
根据征服ajax一书中的例子改写的,那个例子不能检索数据库,希望对大家有所帮助
--------------------------在web.comfig中添加-----------
<httpHandlers>
<add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro" />
</httpHandlers>
----------------------------------------------------------------
-------------------------数据库操作类SqlServerDataBase.cs放在app_code文件夹中---------------
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;
namespace mysqlserver
{
/// <summary>
/// SqlServerDataBase 的摘要说明
/// </summary>
public class SqlServerDataBase
{
private string strError = null;
private int intCount = 0;
public SqlServerDataBase()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 公开方法DBConn,返回数据库连接
/// </summary>
/// <returns></returns>
public SqlConnection DBconn()
{
string strConn = "Server=(local);Database=xldf_rhvac_net;Uid=worldpeace;pwd=oneworld&onexldf";
try
{
return new SqlConnection(strConn);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 公开属性ErrorMessage,返回错误信息
/// </summary>
public string ErrorMessage
{
get
{
return strError;
}
}
/// <summary>
/// 根据查询语句从数据库检索数据
/// </summary>
/// <param name="strSelect">查询语句</param>
/// <param name="SqlConn">数据库连接</param>
/// <returns>有数据则返回DataSet对象,否则返回null</returns>
public DataSet Select(string SelectString, SqlConnection sqlConn)
{
strError = "";
SqlConnection conn;
if (sqlConn == null)
{
conn = DBconn();
}
else
{
conn = sqlConn;
}
try
{
//若数据库连接的当前状态是关闭的,则打开连接
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand(SelectString, conn);
selectCommand.CommandType = CommandType.Text;
mySqlDataAdapter.SelectCommand = selectCommand;
DataSet myDS = new DataSet();
mySqlDataAdapter.Fill(myDS);
return myDS;
}
catch (Exception e)
{
strError = "数据检索失败:" + e.Message;
return null;
}
finally
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
}
}
}
---------------------------------------------------------------------------------------
--------------------------------------前台页面Register.aspx-------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="MyRegister.Register" %>
<%@ Register Assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="Microsoft.Web.UI" TagPrefix="asp" %>
<!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>
<LINK href="../stylesheet.css" _fcksavedurl=""../stylesheet.css"" type="text/css" rel="stylesheet">
<script language="javascript">
function IsUsernameExist_callback(result)
{
var msg = document.getElementById('Message');
var bun = document.getElementById('Button1');
var value = result.value;
if( value == '1' )
{
msg.innerHTML = '用户名未被注册!';
msg.style.color='green';
bun.disabled=false;
return true;
}
else
{
msg.innerHTML = '用户名已被注册!';
msg.style.color='red';
bun.disabled=true;
return false;
}
}
function VerifyUserName(name)
{
MyRegister.Register.GetReturnCode(name, IsUsernameExist_callback);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="middle" style="height: 1px" >
<div >
<asp:Label ID="LbEmail" runat="server" Text="电子邮箱:"></asp:Label>
<asp:TextBox ID="Email" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="Email"></asp:RequiredFieldValidator>
</div>
<div >
<asp:Label ID="LbUserPsw" runat="server" Text="密码:" ></asp:Label>
<asp:TextBox ID="UserPsw" runat="server" TextMode="Password"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate="UserPsw"></asp:RequiredFieldValidator></div>
<div >
<asp:Label ID="LbCheckUserPsw" runat="server" Text="确认密码:" ></asp:Label>
<asp:TextBox ID="CheckUserPsw" runat="server" TextMode="Password"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="*" ControlToValidate="CheckUserPsw"></asp:RequiredFieldValidator></div>
<div >
<asp:Label ID="LbQuestion" runat="server" Text="找回密码问题:"></asp:Label>
<asp:TextBox ID="Question" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*" ControlToValidate="Question"></asp:RequiredFieldValidator></div>
<div>
<asp:Label ID="LbAnswer" runat="server" Text="找回密码答案:"></asp:Label>
<asp:TextBox ID="Answer" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*" ControlToValidate="Answer"></asp:RequiredFieldValidator></div>
<div >
<asp:Label ID="Label1" runat="server" Text="验证码:"></asp:Label>
<asp:TextBox ID="CheckCode" runat="server" Width="85px"></asp:TextBox><a href="javascript:loadimage();"><asp:Image id="Image1" runat="server" ImageUrl="Validate.aspx"></asp:Image></a>
<script type="text/javascript" language="JavaScript">
<!--
function loadimage(){
document.getElementById("Image1").src = "Validate.aspx?"+Math.random();
}
//-->
</script>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="*" ControlToValidate="CheckCode"></asp:RequiredFieldValidator>
</div>
<div>
<asp:Button ID="Button1" runat="server" Text="确定" OnClick="Button1_Click" /></div>
<div class="text">
<asp:Label ID="Message" runat="server" ></asp:Label></div>
</div>
</form>
</body>
</html>
--------------------------------------------------------------------------------------------------
------------------------------------后台页面Register.aspx.cs---------------------------
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;
using mysqlserver;
namespace MyRegister
{
public partial class Register : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox Email1;
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(Register));
Email.Attributes.Add("OnKeyUp", "VerifyUserName(this.value)");
}
[AjaxPro.AjaxMethod]
public string GetReturnCode(string strName)
{
if (!IsUsernameExist(strName))
{
return "1";
}
else
{
return "0";
}
}
private bool IsUsernameExist(string strUsername)
{
bool bRet = true;
SqlServerDataBase db = new SqlServerDataBase();
DataSet ds = db.Select("select * from ypCompanyInfo where CompanyName = '" + strUsername + "'", null);
if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
{
bRet = false;
}
else
{
bRet = true;
}
return bRet;
}
protected void Button1_Click(object sender, EventArgs e)
{
string VNum = CheckCode.Text;
string myEmail = Email.Text.Trim();
if (VNum != Session["VNum"].ToString() || Session["VNum"].ToString() == null)
{
Message.Text = "验证码错误!";
}
else
{
Response.Redirect("../default.aspx");
}
}
}
}
---------------------------------------------------------------------------------
所有的文件都在这了,因为自己也是新手,同时把改写代码过程中遇到的问题说一下
1、类的实例化,也就是如何调用数据库操作类,注意要引用类的命名空间,主要是c#.net的知识。
2、要更改web.config文件,在Page_Load里注册,在使用时加上[AjaxPro.AjaxMethod]。