Auto complete search box using JQuery autocomplete plugin in MVC 5

Ankaprasad
Posted by Ankaprasad under jQuery category on | Points: 40 | Views : 1851
By using jquery auto complete plugin we can achieve the following requirements.

1. Implement auto complete search text box.
2. provide server side search ( every time it will search from the database ).
3. Create generic function for better re-usability.

Function AutoCompleteSearch(matchFieldName, resultFieldName, entityName) {
$('#' + matchFieldName).autocomplete({
source: function (request, response) {
$.ajax({
url: "/LookUp/AutoSearch", // URL
type: "GET",
dataType: "json",
cache: false,
data: { entity: entityName, filter: request.term },
success: function (data) {
if (!data.length) {
var result = [{ label: 'No matches found', value: response.term }];
response(result);
}
else {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name, id: item.Id };
}))
}
}
})
},
minLength: 3,
select: function (event, ui) {
$('#' + resultFieldName).val(ui.item.id);
}
}).autocomplete("widget").addClass("autocomplete-suggestions");
},

The following code will show how to call the auto complete function from the view
 $(function () {
AutoCompleteSearch("txtCompanyUniversity", "hdnCompanyUniversityId", 1);
});


We can set the css class to Auto complete text boxes as shown below.

$('#' + matchFieldName).autocomplete({
}).autocomplete("widget").addClass("autocomplete-suggestions");

CSS :
 .autocomplete-suggestions {
max-height: 200px;
padding: 1px;
overflow: auto;
}


Design the controller as shown below
public JsonResult AutoSearch(string entity, string filter)
{
filter = filter.ToLower();
if (Convert.ToInt32(entity) == Convert.ToInt32(LookUp.LookUpEntity.Account))
{
// Get the search results by passing the search text ( here filter as search text )
List<AutoSearch> records = new Biz.Common().GetAccountsForSearch(filter);

return Json(records, JsonRequestBehavior.AllowGet);
}
return null;

}

Comments or Responses

Login to post response