標籤:exe pwd ext func 說明 log web nec tle
功能說明:當使用者在使用者名稱輸入框輸入字元並焦點離開此輸入框時,自動到資料庫使用者表中驗證此使用者名稱是否已被註冊,如果已被註冊,顯示【不可用】,反之,顯示【可用】,期間頁面不重新整理,讀者也可以考慮將提示文字換成圖片等更佳體驗的提示方式。
(只是的個Demo,沒有考慮諸如Sql注入等問題,期間參考了網上的個別關於ICallbackEventHandler使用的案例。這個Demo是今天在首頁看了某個大蝦關於用ICallbackEventHandler無重新整理擷取伺服器時間後做的,文章地址忘了,呵呵~,等找到後補上)。
前台代碼:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ver.aspx.cs" Inherits="Ver" %> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3 <html xmlns="http://www.w3.org/1999/xhtml"> 4 <head runat="server"> 5 <title>無標題頁</title> 6 7 <script language="javascript"> 8 function VerName() { 9 //傳給背景參數,在方法RaiseCallbackEvent()中實現10 var message = document.getElementById("txtName").value; 11 var context = ""; 12 <%=sCallBackFunctionInvocation%>;13 } 14 function ShowMessage(Mes, context) { 15 //Mes 是後台GetCallbackResult()的傳回值16 var spMes = document.getElementById("spMes");17 if(Mes == "true") {18 spMes.innerHTML = "可用";19 } 20 else{21 spMes.innerHTML = "不可用";22 }23 24 }25 </script>26 </head>27 <body>28 <form id="form1" runat="server">29 <div>30 使用者名稱:<asp:TextBox ID="txtName" runat="server" onblur="VerName()"></asp:TextBox>31 <span id="spMes"></span>32 <br />33 密 碼:<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>34 </div>35 </form>36 </html>View Code
後台代碼:
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()) == 1) { return "false"; } else { return "true"; } } } //接收前台參數 public void RaiseCallbackEvent(string eventArgument) { userName = eventArgument; } #endregion}
【轉】 ASP.NET使用ICallbackEventHandler無重新整理驗證使用者名稱是否可用