JQuery Autocomplete Example With ASP.NET Webforms

This will be a quick run through of how I implemented autocomplete in a Webforms application.

The data for the autocomplete list is represented in a class.

public class Depot
{
    public string DepotCode { get; set; }
    public string DepotName { get; set; }
}

A WebMethod in a service class is called to retrieve the list. I am keeping the amount of the data small for brevity. In this simple example I am checking what the search term starts with and populating a list with similar values. In a real situation the list being returned from this WebMethod would be generated from a search in a database.

[WebMethod]
public List<Depot> GetDepots(string search)
{
    if (search.StartsWith("11"))
    {
        return new List<Depot>{ 
            new Depot{DepotCode= "1111",DepotName= "London"},
            new Depot{DepotCode= "1122",DepotName= "Birmingham"}
        };
    }
    else
    {
        return new List<Depot>{ 
            new Depot{DepotCode= "0111",DepotName= "London"},
            new Depot{DepotCode= "0122",DepotName= "Birmingham"}
        };
    }
}

This javascript is the magic. The request parameter of the source function contains the search text, in this case the text I enter into the input box. I have set minLength to 2, so 2 characters must be entered for the autocomplete list to appear.

In the success function each item of data is transposed into an object consisting of a value and label property. The label property is the text displayed in the autocomplete list.  When an item in the list is selected the Value property is the text that populates the input box.

$("#txtDepotCode").autocomplete({
    source: function (request, response) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "creditqueryservice.asmx/GetDepots",
            data: "{'search':'" + request.term + "'}",
            dataType: "json",
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item.DepotCode,
                        label: item.DepotCode +' - '+ item.DepotName
                    };
                }));
            },
            error: function (result) {
                alert("Error");
            }
        });
    },
    minLength: 2
});

There could potentially be any number of issues but I got this issue

object doesn't support property or method 'curCSS'

which turned out to be a mismatch between the version of jQuery and the version of jQueryUI. After changing the version of jQueryUI this issue went away.

Leave a Reply