使用AJAX和Page Method进行用户输入时,自动检查用户名是否可用 [英] Check username availability automatically as the user types using AJAX with Page Method

查看:50
本文介绍了使用AJAX和Page Method进行用户输入时,自动检查用户名是否可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我提供一些背景知识,我有一个使用Web表单的C#ASP.NET 3.5网站.我需要实现以下功能:

1.在ASP.NET Web表单中,我有一些输入文本框(名称,姓氏,用户名,电话等).我正在运行一些JQuery验证.

2.当用户要添加新联系人时,当他们键入用户名时,我需要自动告诉他们正在编写的用户名是否可用.

3.我已经有一个存储过程来检查UserName是否可用.

4.我有两个使用Ajax进行UserName可用性检查的示例:一个使用Update Panel,但是它具有我想要的功能(当用户输入UserName并离开输入字段时,该方法将执行UserName检查并显示一个信息).另一个使用Page Method,但是它是由Button触发的.

所以我的问题是,如何混合使用这两种方法,以便可以在使用Ajax和Page方法的用户类型中使用Check UserName可用性?
我正在复制两种方法的源代码:

示例代码

1.使用更新面板

1.a-Default.apsx

First let me give some background, I have an C# ASP.NET 3.5 website using web forms. I need to achivie the following functionality:

1. In a ASP.NET Web form I have some input text boxes (Name, Last Name, Username, Phone, etc.). I have some JQuery validations running.

2. When the users want to add a new contact, when they type the Username I need to automatically tell them if the UserName they are writing is available or not.

3. I already have an Stored Procedure to check if the UserName is available or not.

4. I have 2 different examples of UserName Availability check using Ajax: one uses Update Panel, but it has exactly the functionality that I want (when the user inputs the UserName and leaves the input field, the Method executes the UserName check and displays a message). The other one uses Page Method but it is triggered by a Button.

So my question is, how can I mix this 2 approaches so I can have a Check UserName availability as the user types using Ajax and Page Method???

I am copying the source code I have for both approaches:

Example Code

1. Using Update Panel

1.a - Default.apsx

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Check Username availability Using Ajax</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <asp:ScriptManager ID="scriptmanager1" runat="server"> 
    </asp:ScriptManager> 
    <script type="text/javascript"> 
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler); 
    function BeginRequestHandler(sender, args) 
    { 
        var state = document.getElementById('loadingdiv').style.display; 
        if (state == 'block') 
        { 
                    document.getElementById('loadingdiv').style.display = 'none'; 
        } 
 
                else 
        { 
                    document.getElementById('loadingdiv').style.display = 'block'; 
                } 
 
        args.get_postBackElement().disabled = true; 
    } 
</script> 
     <div> 
     
     <asp:UpdatePanel ID="PnlUsrDetails" runat="server"> 
    <ContentTemplate> 
    <table> 
    <tr> 
    <td> 
    UserName: 
    </td> 
    <td> 
       <asp:TextBox ID="txtUsername" runat="server" AutoPostBack="true" ontextchanged="txtUsername_TextChanged"/> 
    </td> 
    <td> 
      <div id="checkusername"  runat="server"  Visible="false"> 
        <asp:Image ID="imgstatus" runat="server" Width="17px" Height="17px"/> 
        <asp:Label ID="lblStatus" runat="server"></asp:Label> 
    </div> 
    </td> 
    </tr> 
    </table> 
    <div class="waitingdiv" id="loadingdiv" style="display:none; margin-removed5.3em"> 
    <img src="LoadingImage.gif" alt="Loading" />Please wait... 
    </div> 
    </ContentTemplate> 
    </asp:UpdatePanel> 
    </div> 
    </form> 
</body> 
</html>



1.b-Default.aspx.cs



1.b - Default.aspx.cs

using System; 
using System.Configuration; 
using System.Data; 
using System.Data.SqlClient; 
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; 
 
public partial class _Default : System.Web.UI.Page  
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     
    } 
 
    protected void txtUsername_TextChanged(object sender, EventArgs e) 
    { 
        if(!string.IsNullOrEmpty(txtUsername.Text)) 
        { 
            SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=FromTheBucketDB;Persist Security Info=True;User ID=sa;PASSWORD=mysa;"); 
            con.Open(); 
            SqlCommand cmd = new SqlCommand("select * from tbUsers where username=@Name", con); 
            cmd.Parameters.AddWithValue("@Name", txtUsername.Text); 
            SqlDataReader dr = cmd.ExecuteReader(); 
            if (dr.HasRows) 
            { 
                checkusername.Visible = true; 
                imgstatus.ImageUrl = "NotAvailable.jpg"; 
                lblStatus.Text = "UserName Already Taken"; 
                System.Threading.Thread.Sleep(2000); 
            } 
             
            else 
            { 
                checkusername.Visible = true; 
                imgstatus.ImageUrl = "Icon_Available.gif";  
                lblStatus.Text = "UserName Available"; 
                System.Threading.Thread.Sleep(2000); 
            } 
        } 
 
        else 
        { 
            checkusername.Visible = false; 
        } 
    } 
}



2.使用分页方法

2.a-Default.aspx



2. Using Page Method

2.a - Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head  runat="server"> 
    <title></title> 
<script type = "text/javascript"> 
function ShowAvailability() { 
    PageMethods.CheckUserName(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess); 
} 
function OnSuccess(response) { 
    var mesg = document.getElementById("mesg"); 
    switch (response) { 
        case "true": 
            mesg.style.color = "green"; 
            mesg.innerHTML = "Available"; 
            break; 
        case "false": 
            mesg.style.color = "red"; 
            mesg.innerHTML = "Not Available"; 
            break; 
        case "error": 
            mesg.style.color = "red"; 
            mesg.innerHTML = "Error occured"; 
            break; 
    } 
} 
function OnChange(txt) { 
    document.getElementById("mesg").innerHTML = ""; 
} 
</script> 
</head> 
<body style = "font-family:Arial; font-size:10pt"> 
<form id="form1"  runat="server"> 
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true"> 
</asp:ScriptManager> 
<div> 
    UserName : 
    <asp:TextBox ID="txtUserName" runat="server" 

        onkeyup = "OnChange(this)"></asp:TextBox> 
    <input id="btnCheck" type="button" value="Show Availability" 

         önclick = "ShowAvailability()" /> 
    <br /> 
    <span id = "mesg"></span> 
</div> 
</form> 
</body> 
</html>



2.b-Default.aspx.cs



2.b - Default.aspx.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Configuration; 
using System.Data; 
 
public partial class _Default : System.Web.UI.Page  
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
 
    } 
 
    [System.Web.Services.WebMethod] 
    public static string CheckUserName(string userName) 
    { 
        string returnValue = string.Empty; 
        try 
        { 
            string consString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString; 
            SqlConnection conn = new SqlConnection(consString); 
            SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn);             
            cmd.CommandType = CommandType.StoredProcedure; 
            cmd.Parameters.AddWithValue("@UserName", userName.Trim()); 
            conn.Open(); 
            returnValue = cmd.ExecuteScalar().ToString(); 
            conn.Close();   
        } 
        catch 
        { 
            returnValue = "error"; 
        } 
        return returnValue;  
    } 
}

推荐答案



我了解您的需求,实现此目标的一种方法是使用jquery执行回调/事件,如下所示:

Hi,

I understand what you are after and one way to achieve this is to execute a callback / event using jquery like so:


(' #usernametextbox' span>).keydown(函数(e){ // /您在此处的回调/事件调用 });
('#usernametextbox').keydown( function(e){ /// your callback / event call here });



我还没有完成完整的示例,因为我想警告您类似的事情.

如果您有一次检查,每次按键都执行一个方法和存储过程,那么如果多个用户在做同一件事,或者您在数据库中有成千上万的用户没有正确的索引,则很快就会遇到性能问题.

您最好以自己的方式进行操作.我个人会在单击按钮时执行此操作,因为可以使用其他方法将其包装起来并立即进行全部验证.

用户名检查的另一个问题是,如果它用于公共站点,并且您的站点包含敏感数据(例如个人详细信息等),则用户名检查很容易违反安全性.可以通过发现用户名(通过告诉您已经使用了哪些用户名就可以简化登录过程的一半),然后采取一些蛮横的策略来进行登录.可能不是您网站的问题,但始终值得质疑.

无论如何希望这会有所帮助.



I have not completed the full example because I wanted to warn you over things like this.

If you have a check that executes a method and stored procedure every key press you will soon run into performance issues if multiple users are doing the same thing and or you have many thousands of users in a database that does not have correct indexing for example.

You really are better off doing it the way you have it. Personally I would do it on the button click as this can be wrapped up using other methods and validate all at once.

Another issue with username checking is that if it is for a public site and your site contains sensitive data such as personal details etc, username checking is prone to security breaches. Breaches can be made by discovering a username (half of the logon process which is made easy by telling you which usernames have already been used) and then some brute force tactics to login. May not be an issue for your site but always worth questioning.

Anyway Hope this helps.


这篇关于使用AJAX和Page Method进行用户输入时,自动检查用户名是否可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆