View:
@{
ViewBag.Title = "Home Page";
}
<label for="somevalue">Some value:</label>
<input type="text" id="somevalue" name="somevalue" data-autocomplete-url="@Url.Action("AutoComplete")"/>
@section
Scripts {
@Scripts.Render("~/bundles/jqueryval")
<link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('*[data-autocomplete-url]')
.each(function () {
$(this).autocomplete({
source: $(this).data("autocomplete-url")
});
});
});
</script>
}
Controller:
public ActionResult Autocomplete(string term)
{
var items = new[] { "Apple", "Pear", "Banana", "Pineapple", "Peach" };
var filteredItems = items.Where(
item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase)
>= 0
);
return Json(filteredItems, JsonRequestBehavior.AllowGet);
}