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