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
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.
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
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
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
The figure below describes the JQuery AJAX method’s syntax which will be used to call our Server Side method.
And finally here are the Client Side functions that will be used
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
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
Visual Studio 2008 : CallingServerSideMethodsJQuery.zip (24.52 kb)
Visual Studio 2005 : CheckUserNameAvailabilityVS05.zip (23.87 kb)
SQL Server 2005 Sample Database : Database.zip (204.84 kb)