Proxy > Gmail Facebook Yahoo!

Check UserName Availability in ASP.Net using JQuery



Many times it was asked to me to provide an AJAX based example to Check User Name Availability using AJAX in ASP.Net. Before I have already written an article but it was lacking Server Side code. This one is a bit different from it as here I’ll be using JQuery to make AJAX Calls to the server. Thus I’ll also explain how to call server side methods or functions directly using JQuery in ASP.Net


Database

For this example I have created a sample database called dbUsers with a table called Users with the following structure


User Table SQL Server 2005 Database : Check whether username already exists in asp.net



Secondly I have created the following stored procedure that will check the database for the user name requested and will return true if user name is available and false in case it is not.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE spx_CheckUserAvailability
      @UserName VARCHAR(50)
AS
BEGIN
      SET NOCOUNT ON;
      IF NOT EXISTS
            (SELECT * FROM Users
             WHERE UserName = @UserName
            )
            SELECT 'true'
      ELSE
            SELECT 'false'
END
GO



Server Side

Server side I have created a method which accepts the user name as string and returns the status returned by the stored procedure based on the availability     


C#

[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;
}



VB.Net

    <System.Web.Services.WebMethod()> _
Public Shared Function CheckUserName(ByVal userName As String) As String
   Dim returnValue As String = String.Empty
   Try
      Dim consString As String = ConfigurationManager _
            .ConnectionStrings("conString").ConnectionString
      Dim conn As New SqlConnection(consString)
      Dim cmd As 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"
   End Try
   Return returnValue
End Function


As you’ll notice that I am simply calling the stored procedure spx_CheckUserAvailability and returning the value returned by the stored procedure.

Now we’ll call this function using JQuery. There are three important points that you need to take care if a function needs to be called using JQuery

1. It should be public.

2. It should be declared as static in C# and Shared in VB.Net

3. It should be defined as Web Service WebMethod

Once all this is done we are ready to write client side code. You can download the JQuery library using the link below

Download JQuery


Client Side


Below is the HTML Markup of the page. I have placed an ASP.Net TextBox for the user to enter user name, a HTML button for invoking the JQuery method and a HTML SPAN to display the messages

<form id="form1" runat="server">
<div>
    UserName :
    <asp:TextBox ID="txtUserName" runat="server"
        onkeyup = "OnChange(this)"></asp:TextBox>
    <input id="btnCheck" type="button" value="Show Availability"
        onclick = "ShowAvailability()" />
    <br />
    <span id = "mesg"></span>
</div>
</form>



The figure below describes the JQuery AJAX method’s syntax which will be used to call our Server Side method.


Calling Server Side Page Methods using JQuery AJAX in ASP.Net



And finally here are the Client Side functions that will be used

<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowAvailability() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/CheckUserName",
        data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response);
        }
    });
}
function OnSuccess(response) {
    var mesg = $("#mesg")[0];
    switch (response.d) {
        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) {
   $("#mesg")[0].innerHTML = "";
}
</script>


As you’ll notice above I am simply calling the CheckUserName Server side function in CS.aspx page (for VB.Net VB.aspx) and passing the TextBox value as parameter. Secondly I have defined the success method OnSuccess that will be called handle the response returned by the Server.


Below is the screenshot of the sample application


Checking username availability in ASP.Net and SQL Server 2005 database using JQuery



Note: For this article I have used Visual Studio 2008. In order to use this functionality in Visual Studio 2005 you have to install AJAX Extensions and Add ScriptManager to the page. Also instead of response.d you’ll have to check for response for the returned values


For reference I have attached the sample code in VB.Net and C# for both VS 2005 and VS 2008 versions. You can download them using the links below






SQL Server 2005 Sample Database : Database.zip (204.84 kb)


Responses

0 Respones to "Check UserName Availability in ASP.Net using JQuery"


Send mail to your Friends.  

Expert Feed

 
Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar