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 PageMethods to make AJAX Calls to the server. Thus I’ll also explain how to call server side methods or functions directly using ASP.Net AJAX ScriptManager PageMethods in ASP.Net
Database
For this example I have created a sample database called dbUsers with a table called Users with the following structure
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 ASP.Net AJAX ScriptManager PageMethods. There are three important points that you need to take care if a function needs to be called using PageMethods
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.
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 JavaScript 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>
Here are the Client Side functions that will be used to call the Server Side Methods that will verify whether the Username entered by the user exists or not.
<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>
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
For reference I have attached the sample code in VB.Net and C# along with the sample database which you can directly attach to your SQL Server Instance. You can download them using the link below
CheckUserNameAvailabilityusingPageMethodsinASP.Net.zip