Reputation: 105
I'm trying to add the jquery autocomplete on my dropDownList with the @url.action, but for some reason it doesn't work. It looks like I have all neccesary jquery loaded. I've tried everything (at least the one I've found in the site or in google).
My HTML + js:
<input id="test" name="test" />
@section scripts
{
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/autocomplete.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#test').autocomplete({
source: '@Url.Action("GetCitiesForAutocomplete", "Students")'
});
});
</script>
}
My Controller Students:
public JsonResult GetCitiesForAutocomplete(string term)
{
return Json(GetCities()
.Where(x=>x.Text.ToLower()
.Contains(term.ToLower())), JsonRequestBehavior.AllowGet);
}
private List<SelectListItem> GetCities()
{
return new List<SelectListItem>
{
new SelectListItem {Text = "Jerusalem", Value = "0"},
new SelectListItem {Text = "Haifa", Value = "1"},
new SelectListItem {Text = "Tel Aviv", Value = "2"},
new SelectListItem {Text = "Katzrin", Value = "3"},
new SelectListItem {Text = "Beer Sheva", Value = "4"},
new SelectListItem {Text = "Netanya", Value = "5"}
};
}
My question is: How i do autocomplete in my dropdownlist only with the text in list.
For ex: If i have press on 'je' -> i get 'Jerusalem'
If i have press on 'te' -> i get 'Tel Aviv'
Thanks.
Upvotes: 0
Views: 449
Reputation: 333
Change the GetCitiesForAutoComplete method to return all cities. Autocomplete will handle the filtering.
public JsonResult GetCitiesForAutocomplete()
{
return Json(GetCities(), JsonRequestBehavior.AllowGet);
}
Upvotes: 1