jQuery UI Autocomplete Widget Using ASP.Net Generic Handler

Objective: Our main purpose is to suggest data in a TextBox when a user enters only some text into it. This data will be fetched using a table stored in the SQL Database. So, we will do some ADO.NET operations.

Solution: We can do this using a jQuery UI Autocomplete Widget. We will use a generic handler to fetch data from the database. Let's have a look in action.

Step 1

Create an Empty ASP.NET web application in Visual Studio and name it whatever you like. I named it "jQueryAutocompleteWidgetWithASP".

Step 2

We need to download the jQuery UI files from its official website www.jqueryui.com/download. Visit the website and select the Autocomplete checkbox and go to the bottom of the page and download the files. Extract the downloaded file and copy the images folder and the jquery-ui.js and jqueryui.css files to your ASP.NET web application.

Step 3

Download the jQuery file from www.jquery.com and also copy it to your solution.

An alternative to the preceding 2 steps is to just download the files from the NuGet package manager as shown below. I am using this method in my project.

Step 4

Create a database with the following script in the SQL Server.

Code Snippet

  5. CREATE TABLE [dbo].[Employee] (  
  6.     [Name]        NVARCHAR (50) NULL,  
  7.     [Designation] NVARCHAR (50) NULL  
  8. );  

Code Snippet

  1. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Mark', N'Software Developer')  
  2. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Amalie', N'Software Developer')  
  3. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Boston', N'Software Developer')  
  4. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Cathie', N'Software Developer')  
  5. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Donaldo', N'Software Developer')  
  6. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Easter', N'Software Developer')  
  7. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Faraday', N'Software Developer')  
  8. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Goldo', N'Software Developer')  
  9. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Harmoine', N'Software Developer')  
  10. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Instern', N'Software Developer')  
  11. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Jane', N'Software Developer')  
  12. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Kalis', N'Software Developer')  
  13. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Lister', N'Software Developer')  
  14. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Nicholas', N'Software Developer')  
  15. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Peter', N'Software Developer')  
  16. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Mark Hastings', N'Software Developer')  
  17. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Amalie Loren', N'Software Developer')  
  18. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Boston Cristopher', N'Software Developer')  
  19. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Cathie Crew', N'Software Developer')  
  20. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Donaldo Duck', N'Software Developer')  
  21. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Easter Caster', N'Software Developer')  
  22. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Faraday Joseph', N'Software Developer')  
  23. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Goldo Jene', N'Software Developer')  
  24. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Harmoine Creanjure', N'Software Developer')  
  25. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Instern Calis', N'Software Developer')  
  26. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Jane Austen', N'Software Developer')  
  27. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Kalis Cris', N'Software Developer')  
  28. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Lister Lane', N'Software Developer')  
  29. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Nicholas Nistola', N'Software Developer')  
  30. INSERT INTO [dbo].[Employee] ([Name], [Designation]) VALUES (N'Peter Parker', N'Software Developer')  

Code Snippet

  1. CREATE procedure GetData   
  2. @QueryString nvarchar(50)  
  3. As  
  4. Begin  
  5.     Select Name from Employee where Name like '%' + @QueryString + '%'  
  6. End  

Step 5

Add a Connection String to the preceding created database using the following code. Put this code in the web.config file of your project.

Code Snippet

  1. <?xml version="1.0"?>    
  2. <configuration>    
  3.  <system.web>    
  4.    <compilation debug="true" targetFramework="4.5" />    
  5.    <httpRuntime targetFramework="4.5" />    
  6.  </system.web>    
  7.  <connectionStrings>    
  8.    <add connectionString="Data Source=.;Initial Catalog=SampleDB;Integrated Security=SSPI" providerName="System.Data.SqlClient" name="DB"/>    
  9.  </connectionStrings>    
  10. </configuration>  

Step 6

Add a Generic Handler to your project and name it "employeeHandler".

Step 7

Add the following code to the "employeeHandler.ashx.cs".

Code Snippet

  1. using System.Collections.Generic;    
  2. using System.Configuration;    
  3. using System.Data;    
  4. using System.Data.SqlClient;    
  5. using System.Web;    
  6. using System.Web.Script.Serialization;    
  8. namespace jQueryAutocompleteWidgetWithASP    
  9. {    
  10.     public class employeeHandler : IHttpHandler    
  11.     {    
  13.         public void ProcessRequest(HttpContext context)    
  14.         {    
  15.             string QueryString = context.Request["term"];    
  16.             List<string> listEmployee = new List<string>();    
  17.             string CS = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;    
  18.             using (SqlConnection con = new SqlConnection(CS))    
  19.             {    
  20.                 con.Open();    
  21.                 SqlCommand cmd = new SqlCommand("GetData", con);    
  22.                 cmd.CommandType = CommandType.StoredProcedure;    
  23.                 cmd.Parameters.Add(new SqlParameter()    
  24.                 {    
  25.                     ParameterName = "@QueryString",    
  26.                     Value = QueryString    
  27.                 });    
  29.                 SqlDataReader DR = cmd.ExecuteReader();    
  30.                 while (DR.Read())    
  31.                 {    
  32.                     listEmployee.Add(DR["Name"].ToString());    
  33.                 }    
  34.             }    
  35.             JavaScriptSerializer JS = new JavaScriptSerializer();    
  36.             context.Response.Write(JS.Serialize(listEmployee));    
  37.         }    
  38.         public bool IsReusable    
  39.         {    
  40.             get    
  41.             {    
  42.                 return false;    
  43.             }    
  44.         }    
  45.     }    
  46. }    

Step 8

Add a webform to your project and name it "Demo.aspx".

Step 9

Add the following code to the HTML source of the preceding added webform.

Code Snippet

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="jQueryAutocompleteWidgetWithASP.Demo" %>  
  3. <!DOCTYPE html>  
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <link href="Content/themes/base/all.css" rel="stylesheet" />  
  9.     <script src="Scripts/jquery-2.1.4.js"></script>  
  10.     <script src="Scripts/jquery-ui-1.11.4.js"></script>  
  11.     <script type="text/javascript">  
  12.         $(document).ready(function () {  
  13.             $('#txtName').autocomplete({  
  14.                 source: 'employeeHandler.ashx'  
  15.             });  
  16.         });  
  17.     </script>  
  18. </head>  
  19. <body>  
  20.     <form id="form1" runat="server">  
  21.         Employee Name :  
  22.         <asp:TextBox ID="txtName" runat="server">  
  23.         </asp:TextBox>  
  25.     </form>  
  26. </body>  
  27. </html>  

Step 10

Finally Run the project by pressing the F5 Key. You will see the following result.

The following is the description of the SQL Script:

  1. We simply create a table with some sample data.
  2. Create a Stored Procedure to retrieve names from the table and we are using "@QueryString" as the parameter to filter the data. Also we used "%" that is a wildcard of SQL. It fetches all the names that meets the conditions.

Description of Web.config: We added a connection string to this file so that it will be easy for us to connect to our database.

The following describes the Generic Handler code:

  1. In the beginning we will add the namespaces to obtain classes. We have added four additional namespaces. Three are for ADO.NET connectivity and the last one is for serialization.
  2. We use the context parameter of the ProcessRequest function. We defined a key for it as "term" and save it in a string variable. Remember, use the key "term" because our jQuery Widget will recognise this only. This is specified in the API documentation of the widget on api.jqueryui.com.
  3. A simple List object is created so that we can store the list of names retrieved from database.
  4. A simple ADO.NET code is used to read the data.
  5. Finally, the JavaScriptSerializer class object is created and context will write the response to List that we created in Step 3.

The following describes the HTML page with jQuery:

  1. Use a TextBox on the page.
  2. Include the JavaScript files and CSS files in the page.
  3. Add a script tag.
  4. Use the jQuery DOM Ready function to invoke an anonymous function and inside it, we are using the autocomplete method of the jQuery Id selector element.
  5. The "source" JSON object of the autocomplete method executes the handler that we created and the QueryString is passed to the handler.
  6. Using QueryString as the parameter, the Stored Procedure executes and gives us the list of names.

If you like my tutorial, please comment.

Also follow me on Facebook, Twitter and LinkedIn. Also Like my Facebook page, www.fb.com/the technewsinform