ASP.NET Autocomplete Textbox Using jQuery, JSON and AJAX

Requirement 

We need a textbox in which when a user types the name of a country, it automatically shows suggestions as soon as the user starts typing a word. Also with the suggestion, we want the country flag to appear against each country in the suggestion.

Solution

Step 1: Download some sample images of flags of some countries from the internet. I have already downloaded some of the images.

Step 2: Create a table in a database that stores the path of flags along with the country names. Use the following SQL Script to achieve this.
  1. CREATE DATABASE jQueryUIDemo  
  2.    
  3. USE jQueryUIDemo  
  4.    
  5. CREATE TABLE [dbo].[jQueryDemo] (  
  6.     [Id]          INT            IDENTITY (1, 1) NOT NULL,  
  7.     [CountryName] NVARCHAR (50)  NOT NULL,  
  8.     [IconPath]    NVARCHAR (MAXNOT NULL,  
  9.     PRIMARY KEY CLUSTERED ([Id] ASC)  
  10. );  
  11.    
  12. CREATE procedure [dbo].[spGetCountriesDetailsWithIcons]  
  13. @term nvarchar(max)  
  14. as  
  15. begin  
  16.     select * from jQueryDemo where CountryName like @term + '%'  
  17. end  
  18.    
  19. SET IDENTITY_INSERT [dbo].[jQueryDemo] ON  
  20. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (1, N'Australia', N'/Icons/australia.gif')  
  21. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (2, N'Canada', N'/Icons/canada.gif')  
  22. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (3, N'China', N'/Icons/china.gif')  
  23. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (4, N'England', N'/Icons/england.gif')  
  24. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (5, N'India', N'/Icons/india.gif')  
  25. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (6, N'Ireland', N'/Icons/ireland.gif')  
  26. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (7, N'Malaysia', N'/Icons/malaysia.gif')  
  27. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (8, N'Mexico', N'/Icons/mexico.gif')  
  28. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (9, N'Nepal', N'/Icons/nepal.gif')  
  29. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (10, N'Pakistan', N'/Icons/pakistan.gif')  
  30. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (11, N'Poland', N'/Icons/poland.gif')  
  31. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (12, N'Portugal', N'/Icons/portugal.gif')  
  32. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (13, N'Russia', N'/Icons/russia.gif')  
  33. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (14, N'Spain', N'/Icons/spain.gif')  
  34. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (15, N'Sri Lanka', N'/Icons/sri_lanka.gif')  
  35. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (16, N'Turkey', N'/Icons/turkey.gif')  
  36. SET IDENTITY_INSERT [dbo].[jQueryDemo] OFF  
Step 3: Open Visual Studio and create an empty ASP.NET Web application.

Web application

empty tampletes

Step 4: Add a folder named "Icons" and copy all the downloaded images to it. Remember, the name of the folder should be same as that of the path that you have saved in the Database table.

Step 5: Download jQueryUI Autocomplete Widget source files from jQueryUI official website or you can follow the steps to download from my previous article on jQueryUI Autocomplete widget. Copy this downloaded folder to the root directory of the application. We need only the reference of the following files in that downloaded folder.

JQueryUI

Step 6:
Add a class file named "Countries.cs" and replace with the following code.

add new class

class
  1. namespace jQueryUIAutocompleteWithIcons  
  2. {  
  3.    public class Countries  
  4.    {  
  5.       public int Id { getset; }  
  6.       public string CountryName { getset; }  
  7.       public string IconPath { getset; }  
  8.    }  
  9. }  
Step 7: Add the connection strings to connect to the database in the web.config file.
  1. <?xml version="1.0" encoding="utf-8"?>  
  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=.; Database=jQueryUIDemo; Integrated Security=True" name="DBCS" providerName="System.Data.SqlClient"/>  
  9.   </connectionStrings>  
  10. </configuration>  
Step 8: Add an ASP.NET Web service file named "CountriesService.asmx" and replaced it with the following code.

add new item

webservice
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.Web.Script.Serialization;  
  7. using System.Web.Services;  
  8.    
  9. namespace jQueryUIAutocompleteWithIcons  
  10. {  
  11.     [WebService(Namespace = "http://tempuri.org/")]  
  12.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  13.     [System.ComponentModel.ToolboxItem(false)]  
  14.     [System.Web.Script.Services.ScriptService]  
  15.     public class CountriesService : System.Web.Services.WebService  
  16.     {  
  17.         [WebMethod]  
  18.         public void GetCountriesDetails(string term)  
  19.         {  
  20.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  21.    
  22.             List<Countries> countries = new List<Countries>();  
  23.    
  24.             using (SqlConnection con = new SqlConnection(CS))  
  25.             {  
  26.                 SqlCommand cmd = new SqlCommand("spGetCountriesDetailsWithIcons", con);  
  27.                 cmd.CommandType = CommandType.StoredProcedure;  
  28.                 cmd.Parameters.AddWithValue("@term", term);  
  29.                 con.Open();  
  30.                 SqlDataReader dr = cmd.ExecuteReader();  
  31.                 while (dr.Read())  
  32.                 {  
  33.                     Countries country = new Countries();  
  34.                     country.Id = Convert.ToInt32(dr["Id"]);  
  35.                     country.CountryName = dr["CountryName"].ToString();  
  36.                     country.IconPath = dr["IconPath"].ToString();  
  37.                     countries.Add(country);  
  38.                 }  
  39.             }  
  40.             JavaScriptSerializer JS = new JavaScriptSerializer();  
  41.             Context.Response.Write(JS.Serialize(countries));  
  42.         }  
  43.     }  
  44. }  
Press Ctrl + F5 to check that our service is working as expected or not. You will see the following screen.

service

Click the link GetCountriesDetails which is the name of the method that we created in Service code. You will see the following.

GetCountriesDetails

When you enter some characters and press invoke, it will fetch the data from the database using the Stored procedure that we created in SQL.

fetch the data from database

Understanding the code of Web service.
  • We will use the auto implemented properties defined in Countries.cs class file.

  • In the web service we are using the simple ADO.NET connectivity to fetch data using Stored procedure.

  • The data that we get from database is stored in List object of Countries class. So, a list of countries is maintained in it.

  • At the end of code, we are using JavascriptSerializer Class's object which will serialize all the list data into JSON format that we will use in our jQuery code to show suggestions in textbox.

Step 9: Add a new Webform named "Demo.aspx" and add the reference of the following jQuery files to its head section.

jQuery files

Step 10: Add the following code to HTML Source of Demo.aspx page.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="jQueryUIAutocompleteWithIcons.Demo" %>  
  2.    
  3. <!DOCTYPE html>  
  4.    
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <script src="jquery-ui-1.11.4.custom/external/jquery/jquery.js"></script>  
  8.     <script src="jquery-ui-1.11.4.custom/jquery-ui.js"></script>  
  9.     <link href="jquery-ui-1.11.4.custom/jquery-ui.css" rel="stylesheet" />  
  10.     <link href="jquery-ui-1.11.4.custom/jquery-ui.theme.css" rel="stylesheet" />  
  11.     <link href="jquery-ui-1.11.4.custom/jquery-ui.structure.css" rel="stylesheet" />  
  12.     <title>jQueryUI Demo</title>  
  13.     <script type="text/javascript">  
  14.         $(document).ready(function () {  
  15.             $("#countryInput").autocomplete({  
  16.                 minLength: 1,  
  17.                 source: function (request, response) {  
  18.                     $.ajax({  
  19.                         url: "CountriesService.asmx/GetCountriesDetails",  
  20.                         method: "post",  
  21.                         data: { term: request.term },  
  22.                         dataType: "json",  
  23.                         success: function (data) {  
  24.                             response(data);  
  25.                         },  
  26.                         error: function (err) {  
  27.                             alert(err);  
  28.                         }  
  29.                     });  
  30.                 },  
  31.                 focus: updateTextbox,  
  32.                 select: updateTextbox  
  33.             }).autocomplete("instance")._renderItem = function (ul, item) {  
  34.                 return $("<li>")  
  35.                     .append("<img class='imageClass' src=" + item.IconPath + " alt=" + item.CountryName + "/>")  
  36.                     .append('<a>' + item.CountryName + '</a>')  
  37.                     .appendTo(ul);  
  38.             };  
  39.             function updateTextbox(event, ui) {  
  40.                 $(this).val(ui.item.CountryName);  
  41.                 return false;  
  42.             }  
  43.         });  
  44.     </script>  
  45.     <style type="text/css">  
  46.         .imageClass {  
  47.             width: 16px;  
  48.             height: 16px;  
  49.             padding-right: 4px;  
  50.         }  
  51.     </style>  
  52. </head>  
  53. <body>  
  54.     <form id="form1" runat="server">  
  55.         Enter Country Name :  
  56.             <input type="text" id="countryInput" />  
  57.     </form>  
  58. </body>  
  59. </html>  
Step 11: Verify that our Solution Explorer should look like the following image. I mean that all the below mentioned files/folder should be available.

Solution Explorer

Step 12: Now press Ctrl + F5 and you will see that our objective is completed.

see that our objective

enter country name

Understanding the HTML and jQuery Code
  • We have taken a textbox in the body of HTML page.

  • In Jquery code, we have used some properties of AJAX and Autocomplete Widget, to understand their purposes, you can refer to their definitions from jqueryui.com and jquery.com.

Code Explanation:

  • At the very first, in ready function of jQuery, we are finding the textbox using its ID and to that we applied autocomplete function of jQuery.

  • minLength tells that the minimum character to be entered by the user should be one.

  • Source tells what will be the source for autocomplete feature to work, so we created a function that sends the user entered value to our web service which expects a parameter called "term". All this will occur at the request end. When the service completes its work, we specify the method as 'post' which will only work when we get the response from the web service. That's why the function here has two parameters i.e. request and response.

  • As our web service is returning that data in JSON format, so we specify datatype as JSON.

  • The data is term that we send to the service.

  • If the data is success, then we return back data in the function and send it to response parameter of source function.

  • If the error occurs, it will show a JavaScript alert.

  • Focus and select will keep the focus on textbox. This is implemented to show the data in textbox even if we hover mouse cursor over. For this we created a separate function which shows the hovered/selected list item of autocomplete in the textbox.

  • Again we call autocomplete function, to that we call _renderItem method which creates a list of returned data in <li> tag format.

  • RenderItem expects two parameters, ul and item. So, we returned a <li> tag using jQuery and to that we append image tag which shows the image.

  • To the above, we again append the name of country.

  • And we added all this appended data to <ul> and returned the item.

  • We also added some style to set the width and height of the image because image can be of different sizes.

Please read this article on my personal blogs also: debugsolutions and technewsinform. If you liked this article, then please share as much as you can.

Up Next
    Ebook Download
    View all
    Learn
    View all