To implement Autocomplete, you need to install the following package:
link
Assume a TextBox
with Autocomplete
that brings cities, and automatically populate a state according to the state Id. I need to have in my View
the city, 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>
On the Controller, we need to have a Action
that returns a JSON to populate the Autocomplete
information, getting term
as a parameter ( term
in this case is jQuery UI default, and means that it is part of the city name 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);
}