ASP.NET AutoComplete TextBox Using jQuery AJAX

This article explains how to implement an auto-complete textbox in ASP.NET using jQuery AJAX. The following is the SQL Server Table that I will use for fetching the records to display on the auto-complete textbox.

textbox

Step 1 - Create web application.

  1. "Start" - "All Programs" - "Microsoft Visual Studio 2013".
  2. "File" - "New WebSite" - "C#" - "Empty WebSite”.
  3. Provide the website a name, such as "AutoCompleteUsingJQuery" and specify the location.
  4. Then, right-click on Solution Explorer - "Add New Item" - Add Web Form. Name it as “AutoComplete.aspx”.
  5. Drag and drop one TextBox and four labels onto the <form> section of the AutoComplete.aspx page.
  6. Add the following stylesheets as well as scripts in your .aspx page.
    1. <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />  
    2. <link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />  
    3. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>  
    4. <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>  
    Here, I am using CDN library to refer to the scripts.You can also download those libraries and can give a reference in your project.

  7. Now, the AutoComplete.aspx page source code will look like the following code.
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoComplete.aspx.cs" Inherits="AutoCompleteUsingJQueryForCSharpCorner.AutoComplete" %>  
    2.     <!DOCTYPE html>  
    3.     <html xmlns="http://www.w3.org/1999/xhtml">  
    4.   
    5.     <head runat="server">  
    6.         <title></title>  
    7.         <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />  
    8.         <link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />  
    9.         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>  
    10.         <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>  
    11.     </head>  
    12.   
    13.     <body>  
    14.         <form id="form1" runat="server">  
    15.             <div style="width: 300px; margin-top: 50px; height: 23px">  
    16.                 <asp:Label ID="lbl" runat="server" Text="Search"></asp:Label>  
    17.                 <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>  
    18.                 <asp:Button ID="Label1" runat="server" Text="OK" OnClick="btn_click"></asp:Button><br /> <br />  
    19.                 <asp:Label ID="Label2" runat="server" Text="You selected:"></asp:Label>  
    20.                 <asp:Label ID="Label3" runat="server"></asp:Label>  
    21.             </div>  
    22.         </form>  
    23.     </body>  
    24.   
    25.     </html>  

Step 2- Use Entity Framework.

  1. Right click on your Project Name->Add New Item ->Select ADO.NET Entity Data Model
  2. Give it a suitable name and select appropriate table from your respective database.

In my case, the database is MS SQL Server and my table is TblCountry. The created entity model will look like the following.

TblCountry

Step 3- AutoComplete.aspx.cs page will look like this.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Script.Services;  
  6. using System.Web.Services;  
  7. using System.Web.UI;  
  8. using System.Web.UI.WebControls;  
  9. namespace AutoCompleteUsingJQueryForCSharpCorner   
  10. {  
  11.     public partial class AutoComplete: System.Web.UI.Page {  
  12.         protected void Page_Load(object sender, EventArgs e) {}  
  13.             [WebMethod]  
  14.             [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
  15.         public static List < string > GetCountryName(string pre) {  
  16.             List < string > allCompanyName = new List < string > ();  
  17.             using(VishalPrajapatiEntities dc = new VishalPrajapatiEntities()) {  
  18.                 allCompanyName = (from a in dc.TblCountries where a.CountryName.StartsWith(pre) select a.CountryName).ToList();  
  19.             }  
  20.             return allCompanyName;  
  21.         }  
  22.         protected void btn_click(object sender, EventArgs e) {  
  23.             Label3.Text = txtCountry.Text;  
  24.         }  
  25.     }  
  26. }  
In the above code, we are using LINQ and creating the generic list from model.edmx and we will fetch records from the above generic list.

Step 4- Create jQuery AJAX function to call Controller JSON Action Method and invoke autocomplete function on it.
  1. <script type="text/javascript">  
  2.     $(function() {  
  3.         $('#<%=txtCountry.ClientID%>').autocomplete({  
  4.             source: function(request, response) {  
  5.                 $.ajax({  
  6.                     type: "POST",  
  7.                     url: "AutoComplete.aspx/GetCountryName",  
  8.                     data: "{ 'pre':'" + request.term + "'}",  
  9.                     dataType: "json",  
  10.                     contentType: "application/json; charset=utf-8",  
  11.                     success: function(data) {  
  12.                         response($.map(data.d, function(item) {  
  13.                             return {  
  14.                                 value: item  
  15.                             }  
  16.                         }))  
  17.                     },  
  18.                     error: function(XMLHttpRequest, textStatus, errorThrown) {  
  19.                         alert("Error");  
  20.                     }  
  21.                 });  
  22.             }  
  23.         });  
  24.     });  
  25. </script>  
Here, AutoComplete.aspx refers to the main page and GetCountryName refers to the .cs page method. Don't forget to include scripts for the proper functioning of AJAX function.

Now, run the application and type any word. It will auto populate the records which start exactly with the first character you typed, as shown in the following images.

output

output
Note,

 

  • For detailed code, please download the sample zip file.
  • Perform changes in Web.config file as per your server location.
  • You need to use the jQuery library.

I hope this article will be useful for all readers.

Ebook Download
View all
Learn
View all