This is a quick run through of how to implement a jQuery autocomplete with webforms. The lookup data consists of about 600 items and changes very rarely so I want to load the data only once when the page loads rather than sending a query to the database as the user types in the input box.
On the Webform is a input box which will have autocomplete feature.
<div>
<asp:Label ID="Label5" runat="server" Text="Depot Code:" AssociatedControlID="txtDepotCode" />
<asp:TextBox ID="txtDepotCode" runat="server" ClientIDMode="Static" TabIndex="5" />
<asp:TextBox ID="txtDepotName" runat="server" ClientIDMode="Static" TabIndex="6" />
</div>
In this javascript code a webservice is being called to retrieve the items via an ajax call. When the data is returned it is set as the source data for the autocomplete input box.
$(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "creditqueryservice.asmx/GetDepots",
dataType: "json"
}).done(function (response) {
var data = $.map(response.d, function (item) {
return {
value: item.DepotCode,
label: item.DepotCode + ' - ' + item.DepotName
};
});
$("#txtDepotCode").autocomplete({
source: data,
minLength: 2,
select: function(event, ui) {
// do something here. ui parameter holds the values of the item selected
$("#" + this.id).val(ui.item.value);
$("#" + this.id + "name").val(ui.item.DepotName);
return false;
}
});
});
});
The depots are retrieved via a repository (_branchesRepo) variable in the class. Retrieve the data suitable to your application.
[WebMethod]
public List<Depot> GetDepots()
{
var depots = new List<Depot>();
if (depots == null || depots.Count == 0)
{
depots = _branchesRepo.GetBranches();
}
return depots;
}
To validate what the user has entered the autocomplete data can retrieved as in the code below.
var source = $("#txtDepotCode").autocomplete("option", "source");
Now you can compare the value entered with the values in the list. You would really only do this if the user typed into the input box without selecting an item from the matched list.



You must be logged in to post a comment.