Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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
<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

C#
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. Using Page Method

2.a - Default.aspx

HTML
<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

C#
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;  
    } 
}
Posted

1 solution

Hi,

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

JavaScript
$('#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.
 
Share this answer
 
Comments
pavo2005 23-Jul-12 15:06pm    
Hello db7uk, Thank you for you reply. Let me give you a little bit more of information:

The web application is not public, it will be behind a login and password layer, and it will be used by no more that 5 simultaneous users. As you can see security and performance will not be a problem. I just want them to know if what they are typing exists or not in the database.

Now about executing an stored procedure each time a users types something as you mention, I agree it will be too much. But what about when the users leaves the text box? that would be better, don't you think?

About using a button, I really don't want to use that, because I want to give the users a simple web application with only 2 buttons: Add and Cancel. I think to give them a third one (Check username availability) would be too much.

So now that you know more about my needs and a general overview of my web application, can you give me an example of how can I implement this in my web application?


Thanks for all your help, and I hope to hear soon from you.


Greetings
db7uk 23-Jul-12 15:42pm    
Hiya,

Ok that is understood. Yes this is something that could be done if not public. So with that in mind I would suggest the following:

First use the focusout event from Jquery. This would fire every time you the textbox looses focus. Using the below you can then call your stored procedure.

$('#usernametextbox').focusout(function(){
//callback here
});

You may ask how to call the stored procedure using jquery. Well one way would be to create a service or generic handler (ashx) that returns true or false depending on the contents of the text box.

Look at these links for help. If it really is causing a head ache then message back.

http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
http://riderdesign.com/articles/Check-username-availability-with-JQuery-and-ASP.NET.aspx
http://forums.asp.net/t/1661427.aspx/1
http://www.aspsnippets.com/Articles/Check-UserName-Availability-in-ASP.Net-using-JQuery.aspx
pavo2005 23-Jul-12 16:22pm    
Hello db7uk,

Thank you so much for your explanation, I will try to follow the articles that you are sending to me. I will post the code I will be generating for this, so I can have your feed back (if that is ok with you of course).

Have a great day and I will write soon.


Greetings,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900