In this article I will explain with an example, how to check UserName availability in database in ASP.Net using AJAX PageMethods.
 
 
Database
I have made use of the following table Users with the schema as follows.
Check Username Availability in ASP.Net using AJAX PageMethods
 
I have already inserted few records in the table.
Check Username Availability in ASP.Net using AJAX PageMethods
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Stored Procedure
The following Stored Procedure will be used to check whether the supplied UserName exists in the SQL Server database or not.
It will return TRUE if the UserName does not exists in SQL Server database i.e. it is available and it will return FALSE if the UserName exists in the SQL Server database i.e. it is already in use.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[CheckUserAvailability]
      @UserName VARCHAR(50)
AS
BEGIN
      SET NOCOUNT ON;
      IF NOT EXISTS(SELECT UserName FROM Users
                    WHERE UserName = @UserName)
      BEGIN
            SELECT 'TRUE'
      END
      ELSE
      BEGIN
            SELECT 'FALSE'
      END
END
GO
 
 
HTML Markup
The following HTML Markup consists of:
ScriptManager – For enabling AJAX functions.
TextBox – For capturing UserName.
The HTML TextBox has been assigned with an onkeyup event handler which triggers the ClearMessage JavaScript function.
Button – For checking availability of entered UserName.
The HTML Button has been assigned with an onclick event handler which triggers the CheckAvailability JavaScript function.
SPAN – For displaying success or error message.
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Username:
<input id="txtUsername" type="text" onkeyup="ClearMessage()" />
<input id="btnCheck" type="button" value="Show Availability" onclick="CheckAvailability()" />
<br/>
<span id="message"></span>
 
 
Client Side PageMethod implementation
CheckAvailability JavaScript function
When the Button is clicked, the CheckAvailability JavaScript function gets called.
Inside this function, an AJAX call is made to the CheckUserName WebMethod using PageMethods which accepts the UserName as parameter.
When the response is received, based on whether the UserName is available or in use, appropriate message is displayed in the HTML SPAN element.
 
ClearMessage JavaScript function
The ClearMessage JavaScript function gets called when user types in the TextBox, it simply clears the message displayed in the HTML SPAN element.
 
<script type="text/javascript">
    function CheckAvailability() {
        var username = document.getElementById("txtUsername").value;
        PageMethods.CheckUserName(username, function (response) {
            var message = document.getElementById("message");
            if (response) {
                //Username available.
                message.style.color = "green";
                message.innerHTML = "Username is available";
            }
            else {
                //Username not available.
                message.style.color = "red";
                message.innerHTML = "Username is NOT available";
            }
        });
    };
 
    function ClearMessage() {
        document.getElementById("message").innerHTML = "";
    };
</script>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
 
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
 
 
Server Side WebMethod implementation
The CheckUserName WebMethod will be called from the Client side using AJAX PageMethods.
Inside this WebMethod, the UserName is entered in the TextBox is passed as parameter to SqlCommand class object.
Finally, the CheckUserAvailability Stored Procedure is executed using ExecuteScalar function of SqlCommand class and fetched value is returned back to the Client.
Note: For more details on ExecuteScalar function, please refer Understanding SqlCommand ExecuteScalar in C# and VB.Net.
 
C#
[WebMethod]
public static bool CheckUserName(string username)
{
    bool status = false;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("CheckUserAvailability", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UserName", username.Trim());
            con.Open();
            status = Convert.ToBoolean(cmd.ExecuteScalar());
            con.Close();
        }
    }
    return status;
}
 
VB.Net
<WebMethod>
Public Shared Function CheckUserName(ByVal username As String) As Boolean
    Dim status As Boolean = False
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("CheckUserAvailability", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@UserName", username.Trim())
            con.Open()
            status = Convert.ToBoolean(cmd.ExecuteScalar())
            con.Close()
        End Using
    End Using
    Return status
End Function
 
 
Screenshot
Check Username Availability in ASP.Net using AJAX PageMethods
 
 
Browser Compatibility
The above code has been tested in the following browsers.
Microsoft Edge  FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 
Demo
 
 
Downloads