在驗證會員名時使用了Ajax局部無刷新功能。要實現局部無刷新,首先應該添加2個控件,即ScriptManager控件和UpdataPanel控件。ScriptManager控件又稱爲腳本管理控件,它能夠管理Web頁上的腳本。同時使用ScriptManager控件和UpdatePanel控件,可實現界面無刷新的Web環境。ScriptManager控件不但能夠動態創建與Web服務器相關的腳本,而且這些腳本也能支持Web頁上的局部更新功能。
目前比較流行的無刷新驗證會員名的方式是,當用戶輸入會員名後,再單擊其他文本框時,將會自動提示用戶輸入的會員名是否已註冊
實現這種方式首先需要將用來輸入會員名的文本框控件和提示是否已註冊的Label控件添加到UpdatePanel控件中,這樣就可以實現局部更新功能。Label控件提示會員名是否已註冊,主要是通過使用文本框中的txtChanged事件來實現。該事件是在文本框內容發生改變且失去焦點時引發的。必須注意的是,使用該事件還需要將文本框AutoPostBack屬性設置爲True,使文本修改後自動回發到服務器。在TxtChanged事件中通過SQL語句來查詢用戶輸入的會員名是否存在於數據表中,如果存在,則將設置label控件進行提示,否則將提示會員名可以註冊
例:
Register.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
會員名: <asp:TextBox onFocus="tName();" ID="txtName" runat="server" Width="89px" OnTextChanged="txtName_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server" ErrorMessage="用戶名不能爲空" Width="1px"
ControlToValidate="txtName">*</asp:RequiredFieldValidator>
<asp:Label ID="labUser" runat="server" Text="只能輸入數字、字母、下劃線" Width="159px" Font-Size="12px"></asp:Label>
<asp:Label ID="labIsName" runat="server" Font-Size="12px"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Register.aspx.cs
protected void txtName_TextChanged(object sender, EventArgs e)
{
//判斷用戶名是否爲空
if (txtName.Text == "")
{
//使用Label控件給出提示
labIsName.Text = "用戶名不能爲空";
//設置Label控件的顏色
labIsName.ForeColor = System.Drawing.Color.Red;
}
else
{
//調用自定義isNameFormar方法判斷用戶名是否滿足格式要求
if (isNameFormar())
{
//調用isName自定義方法判斷用戶名是否已註冊
if (isName())
{
labIsName.Text = "用戶名已存在!";
labIsName.ForeColor = System.Drawing.Color.Red;
}
else
{
labIsName.Text = "可以註冊!";
labIsName.ForeColor = System.Drawing.Color.Blue;
}
}
else
{
labIsName.Text = "";
}
}
}
protected bool isName()
{
//創建一個布爾型變量並初始化爲false;
bool blIsName = false;
//創建SQL語句,該語句用來判斷用戶名是否存在
string sqlSel = "select count(*) from tb_userInfo where userName='" + txtName.Text + "' ";
//創建數據庫連接
SqlConnection con = new SqlConnection("server=LENOVO-PC//SQLEXPRESS;database=db_Register;uid=sa;pwd=;");
//打開數據庫連接
con.Open();
//創建SqlCommand對象
SqlCommand com = new SqlCommand(sqlSel, con);
//判斷ExecuteScalar方法返回的參數是否大於0,大於表示用戶名已存在
if (Convert.ToInt32(com.ExecuteScalar()) > 0)
{
blIsName = true;
}
else
{
blIsName = false;
}
//返回布爾值變量
return blIsName;
}
protected bool isNameFormar()
{
//創建一個布爾型變量並初始化爲false;
bool blNameFormar = false;
//設置正則表達式
Regex re = new Regex("^//w+$");
//使用Regex對象中的IsMatch方法判斷用戶名是否滿足正則表達式
if (re.IsMatch(txtName.Text))
{
//設置布爾變量爲true
blNameFormar = true;
//設置label控件的顏色
labUser.ForeColor = System.Drawing.Color.Black;
}
else
{
labUser.ForeColor = System.Drawing.Color.Red;
blNameFormar = false;
}
//返回布爾型變量
return blNameFormar;
}