In this article I will show how to check username with jQuery and ASP.NET. This will let the users know if a particular username is available or not during the process when they are filling out the registration form. In tradtional way if you are going with normal postback , that will irritates the user as the passowrds fields would become empty on next reload. So by doing the same in ajax way will give a better user experience and will reduce the user’s effort to retype certain form fields like password, etc again and again. Brief:
Let's start with database part first and create a sample table say "Users" and insert data into it. Below is the script for it:
CREATE TABLE [Users] ( [UserID] INT IDENTITY , [UserName] NVARCHAR(50), [FirstName] NVARCHAR(50), [LastName] NVARCHAR(50), [MiddleName] NVARCHAR(50), [EmailID] NVARCHAR(50) ) GO INSERT INTO Users ( UserName , FirstName , LastName , MiddleName , EmailID ) SELECT dbo.GenerateRandomName(10), dbo.GenerateRandomName(10), dbo.GenerateRandomName(10), dbo.GenerateRandomName(10), dbo.GenerateRandomName(10)+'@'+ dbo.GenerateRandomName(3)+'.com' GO 500
After running the insert script shown above you will see the following screen in the message window of query analyzer which will be telling you "Batch execution completed 500 times" which means we have inserted 500 rows in our "Users" table.
Above you must be wondering what is "GenerateRandomName" function ? I have used that user defined function so as to create a random name and by "GO 500" I have made the insert script to run 500 times. Below is the script of function. Note in this function I have used "RandNumberView" View. Because I need to use the random number if I had used the rand() simply in the function I would have received this error "Invalid use of side-effecting or time-dependent operator in 'rand' within a function". Below is the script for it:
CREATE FUNCTION [GenerateRandomName] ( @LENGTH INT ) RETURNS NVARCHAR(255) AS BEGIN --DECLARE VARIABLES DECLARE @RandomNumber NVARCHAR(255) DECLARE @I SMALLINT DECLARE @RandNumber FLOAT DECLARE @Position TINYINT DECLARE @ExtractedCharacter VARCHAR(1) DECLARE @ValidCharacters VARCHAR(255) DECLARE @VCLength INT --SET VARIABLES VALUE SET @ValidCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' SET @VCLength = LEN(@ValidCharacters) SET @ExtractedCharacter = '' SET @RandNumber = 0 SET @Position = 0 SET @RandomNumber = '' SET @I = 1 WHILE @I < ( @Length + 1 ) BEGIN SET @RandNumber = ( SELECT RandNumber FROM [RandNumberView] ) SET @Position = CONVERT(TINYINT, ( ( @VCLength - 1 ) * @RandNumber + 1 )) SELECT @ExtractedCharacter = SUBSTRING(@ValidCharacters, @Position, 1) SET @I = @I + 1 SET @RandomNumber = @RandomNumber + @ExtractedCharacter END RETURN @RandomNumber END GO CREATE VIEW [RandNumberView] AS SELECT RAND() AS [RandNumber]
To verify it let's run the select query on "Users" table and you will see the below screen after running it. I have just displayed the screen for few records so as to get it fit in this article.
Let's start making a stored procedure for checking the existence of username from "Users" table based on the input. Here the existence will be checked based on username column. User will type username and based on that username the availibility of that username will be checked. Stored Procedure:
CREATE PROCEDURE [CheckUserNameAvailability] @UserName VARCHAR(30) AS BEGIN SET NOCOUNT ON IF EXISTS ( SELECT 1 FROM Users WHERE UserName = @UserName ) SELECT '1' ELSE SELECT '0' SET NOCOUNT OFF END GO
ASPX code:
<%@ Page Language="C#" AutoEventWireup="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <style type="text/css"> .available { color: Green; } .used { color: Red; } .required { color: Red; } .hide { display:none; } </style> <script type="text/javascript"> var emptyUserNameMessage = 'Please enter the username'; var progressUserNameMessage = 'Checking...'; var availableUserNameMessage = 'Username is available'; var usedUserNameMessage = 'Username has been taken'; $(function() { var userNameAvailabilityLabel = $('#<%= UserNameAvailabilityLabel.ClientID %>'); $('#<%= UserNameAvailabilityButton.ClientID %>').click(function() { var userNameTextBox = $('#<%= UserNameTextBox.ClientID %>'); var userName = userNameTextBox.val(); if ($.trim(userName) == '') { userNameAvailabilityLabel .removeClass() .addClass('required') .html(emptyUserNameMessage); } else { userNameAvailabilityLabel.html(''); $('#ProgressDiv').show(); $.ajax({ type: 'POST', url: 'Sample.asmx/CheckUserNameAvailability', data: '{userName: \'' + userNameTextBox.val() + '\'}', contentType: 'application/json; charset=utf-8', dataType: 'json', success: OnCheckUserNameAvailabilitySuccess, error: OnCheckUserNameAvailabilityError }); } return false; //Prevent postback }); function OnCheckUserNameAvailabilitySuccess(response) { $('#ProgressDiv').hide(); if (response != null && response.d != null) { var data = response.d; switch (data) { case 0: userNameAvailabilityLabel .removeClass() .addClass('available') .html(availableUserNameMessage); break; case 1: userNameAvailabilityLabel .removeClass() .addClass('used') .html(usedUserNameMessage); break; } } } function OnCheckUserNameAvailabilityError(xhr, ajaxOptions, thrownError) { alert(xhr.statusText); } }); </script> </head> <body> <form id="form1" runat="server"> <asp:TextBox ID="UserNameTextBox" runat="server"></asp:TextBox> <span id="ProgressDiv" class="hide"><img src="ajax-loader.gif"/></span> <asp:Label ID="UserNameAvailabilityLabel" runat="server" Text=""></asp:Label> <br /> <asp:Button ID="UserNameAvailabilityButton" runat="server" Text="Check" /> </form> </body> </html>
Let's come to webservice part. The webservice will be called from client side i.e your aspx page for say and the webservice itself will call the database to check the username existence and will send the response back to client according to the database response.Lets create a new webservice and name it "Sample.asmx" :Below is the complete code for it: Webservice code:
using System; using System.Data; using System.Data.SqlClient; using System.Web.Services; /// <summary> /// Summary description for Sample /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class Sample : System.Web.Services.WebService { [WebMethod] public int CheckUserNameAvailability(string userName) { string connectionString = "Data Source=YourServerName; Initial Catalog=YourDatabase; User ID=YourUserName; Password=YourPassword"; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand()) { command.Connection = connection; command.CommandText = "CheckUserNameAvailability"; command.CommandType = CommandType.StoredProcedure; SqlParameter paramUserName = new SqlParameter("@UserName", SqlDbType.VarChar, 30); paramUserName.Value = userName; command.Parameters.Add(paramUserName); connection.Open(); int result = Int32.Parse((command.ExecuteScalar().ToString())); return result; } } } }
Note that the webservice should be marked with [System.Web.Script.Services.ScriptService] attribute. From http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptserviceattribute(v=VS.90).aspx
ScriptServiceAttribute Class indicates that a Web service can be invoked from script. This class cannot be inherited.To invoke a Web service method from ECMAScript (JavaScript), you must apply the ScriptServiceAttribute attribute to the related Web service class. When you apply ScriptServiceAttribute to a Web service class definition that contains one or more methods with WebMethodAttribute applied, the proxy generation script creates a proxy object that corresponds to the Web service class.
Also the method should be marked with [WebMethod] attribute. From http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.aspx Adding this attribute to a method within an XML Web service created using ASP.NET makes the method callable from remote Web clients. This class cannot be inherited.
Below is the screenshot for a username which is avaialble for the user and taken.Here are the two screenshots for the above. One is for what we posted to server and the other one for what we received from server. Below is the screenshot for a username which is avaialble for the user and taken.Here are the two screenshots for the above. One is for what we posted to server and the other one for what we received from server.
That's it above we saw how we checked the username availibility with jQuery and ASP.NET. Doing in ajax way we provided better user experience and consumed less bandwidth while making server calls as we posted only the desired data what we wanted.
Do let me know your feedback, comments.
Very well explained! :)
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18