To implement Autocomplete, you will need to install the following package:
https://www.nuget.org/packages/jquery.ui.combined/
Suppose a TextBox
with Autocomplete
that brings cities, and automatically fills a state according to the state id. I need to have in my View
the city fields, state, Hidden Fields and the script that makes it all work:
@Html.HiddenFor(model => model.CityID)
@Html.HiddenFor(model => model.StateID)
@Html.EditorFor(model => model.CityName)
@Html.TextBoxFor(model => model.StateName, new { disabled = "disabled", @readonly = "readonly" })
<script type="text/javascript">
$(function () {
$("#CityName").autocomplete({
source: '@Url.Action("AjaxFindByName", "Cities")',
minLength: 3,
select: function (event, ui) {
$("#CityName").val(ui.item.value);
$("#CityID").val(ui.item.CityID);
$("#StateName").val(ui.item.StateName);
$("#StateID").val(ui.item.StateID);
return false;
}
});
});
</script>
In Controller, we need to have a Action
that returns a JSON to populate the information from Autocomplete
, receiving a term
as a parameter (term
in this case it is standard jQuery UI, and means it is part of the name of the city in this context):
public JsonResult AjaxFindByName(string term)
{
var cities = context.Cities
.Include(c => c.State)
.Where(c => c.Name.ToUpper().Contains(term.ToUpper())).Take(10)
.AsEnumerable()
.Select(c => new
{
value = c.Name,
CityID = c.CityID,
StateName = c.State.Name,
StateID = c.StateID
});
return Json(cities, JsonRequestBehavior.AllowGet);
}
Something like that? http://jqueryui.com/autocomplete/
– Leonel Sanches da Silva
Yes! But I need to populate this combo box with the database data, and then display the selected data in a grid/form below...
– Ryan Santos