jQuery AutoComplete by Example in ASP.NET

This article helps you to create AutoComplete textbox using jQuery library. This will also give you details about jQuery AutoComplete UI, CSS and select event.

In this example you will create a ASP.NET Web Form application which will connect to Northwind database. If you do not have Northwind database you can download from here. The AutoComplete TextBox's change event will call PageMethod written in WebForm code behind file. This method will get country names from Customer table and return as suggestion for AutoComplete TextBox.


jQuery AutoComplete Widget

jQuery AutoComplete Widget gives pre-populated list of suggestions as user types in input field. You need to provide array of strings as source to this widget. Array can be created by some static values or get values from database. Also you can mention minLength to specify after how many characters input call for suggestions to be made.


jQuery.Ajax() with PageMethod

Go through jQuery Ajax with PageMethod where I described how to call PageMethods using jQuery.Ajax() method.

It has a DropDownList control to display Country and a Table object to display Customer details of selected country. On change event of DropDownList control customer detail will be read from database using jQuery.Ajax() call and append as row to Table object.

You can implement it step by step or download source code here

In this article we will add a TextBox control which will be AutoComplete to suggest countries and replace functionality of existing DropDownList control.


TextBox with AutoComplete

Open Default.aspx page and add a TextBox control. Name it as txtCountry. Whenever user types some characters in txtCountry it will make jQuery.Ajax() to Northwind database and select related Country names which will be associated as source for AutoComplete widget.

                
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
                    
    

WebMethod for GetCountryNames

The method GetCountryNames is a WebMetod meaning that it can be called from client side script code like JavaScript. It accepts parameter keyword and get Country names which contains specific keyword from database. Those country names will be return as array of string to AutoComplete widget.

Add below code in Default.aspx.cs file


[WebMethod]
public static string[] GetCountryNames(string keyword)
{
    List<string> country = new List<string>();  
    string query = string.Format("SELECT DISTINCT Country FROM 
            Customers WHERE Country LIKE '%{0}%'", keyword);

    using (SqlConnection con =
            new SqlConnection("your connection string"))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                country.Add(reader.GetString(0));    
            }
        }
    }
    return country.ToArray();
}
     
     

TextBox Autocomplete event

AutoComplete widget has many properties which you can use to customize your execution and control look and feel.

For this tutorial we will use Source, minLength and Select event.

From Solution Explorer -> Scripts folder open Customer.js. It contains a jQuery method for getting customer from Database and append customer details to Table object.

below jQuery code to Customer.js file.


 $("#MainContent_txtCountry").autocomplete({
    source: function (request, response) {
    var param = { keyword: $('#MainContent_txtCountry').val() };
    $.ajax({
        url: "Default.aspx/GetCountryNames",
        data: JSON.stringify(param),
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataFilter: function (data) { return data; },
        success: function (data) {
            response($.map(data.d, function (item) {
                return {
                    value: item
                }
            }))
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
    },
    select: function (event, ui) {
        if (ui.item) {
            GetCustomerDetails(ui.item.value);
        }
    },
    minLength: 2
});   
          
            

We have added Source method which makes a call to GetCountryNames PageMethod written in code behind file. The return values from method shown as pre populated suggestions for user.

We mentioned minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.

Select event gives you selected value by user. The value can be read by ui.item.value


jQuery AutoComplete Select Event

In this step we will use selected value by user and perform required operation.

For this tutorial you are going to make another jQuery.Ajax() call and get customer details who belongs to selected country.

In Previous step we mention that on selection of value from pre populated list of AutoComplete TextBox we will call jQuery GetCustomerDetails function. It takes Country name as input parameter, make ajax call to WebMethod get Customer details and render in table object.

Add below GetCustomerDetails function in Customer.js


function GetCustomerDetails(country) {
    
$("#tblCustomers tbody tr").remove();

$.ajax({
    type: "POST",
    url: "Default.aspx/GetCustomers",
    data: '{country: "' + country + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
    response($.map(data.d, function (item) {
        var rows = "<tr>"
            + "<td class='customertd'>" + item.CustomerID + "</td>"
            + "<td class='customertd'>" + item.CompanyName + "</td>"
            + "<td class='customertd'>" + item.ContactName + "</td>"
            + "<td class='customertd'>" + item.ContactTitle + "</td>"
            + "<td class='customertd'>" + item.City + "</td>"
            + "<td class='customertd'>" + item.Phone + "</td>"
            + "</tr>";
        $('#tblCustomers tbody').append(rows);
    }))
    },
    failure: function (response) {
        alert(response.d);
    }
});
}
    

GetCustomers PageMethod already written in Default.aspx.cs file.


jQuery AutoComplete ui

You will have to include required jQuery and css files. jQuery AutoComplete UI provides those files, using it your TextBox will perform autocomplete and render suggestions for user.

Add reference to those files in Site.Master file.


<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" 
href="http://ajax.googleapis.com/ajax/libs/jqueryui
        /1.8/themes/base/jquery-ui.css" />
    
<script language="javascript"  type="text/javascript" src=
  "http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
    </script>  

<script language="javascript"  type="text/javascript" src=
  "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js">
    </script> 

<script language="javascript"  type="text/javascript"
 src="Scripts/Customer.js"></script>     
      

jQuery AutoComplete by example in asp.net

Download source code

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by Chinju at 8/28/2015 12:00:00 AM
Nice !
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by Kaspa at 9/29/2015 9:59:00 AM
is there an alternate way to get these source files? The .rar downloads are not working.
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by Laxmikant at 9/29/2015 6:22:00 PM
@Kaspa, sent you through email. Please check your emails
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by Zeel at 10/23/2015 8:12:00 AM
Nice work! I have implemented this in my project and that works in Chrome but not working in IE9. Do you have any solution for that?
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by ver at 2/1/2017 3:33:00 AM
can you send it to me @ vergoody@gmail.com
post comment on dotnetmentors.com
User profile picture on dotnetmentors.com

by Mr. Nobody at 8/13/2017 4:15:00 PM
I had to remove the response() wrapper in the javascript - other than that - great example!
post comment on dotnetmentors.com