0

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.

3
  • Are you using Jquery UI AutoComplete or this one? Commented Feb 22, 2016 at 17:47
  • @MihirSolanki I'm using Jquery UI AutoComplete Commented Feb 22, 2016 at 19:53
  • I think you need to pull the result of @Url.Action("GetCitiesForAutocomplete", "Students") into a JSON object and use that as the source. As it appears, you have autocomplete dong filtering as well as the JSON method. Commented Feb 22, 2016 at 21:31

1 Answer 1

1

Change the GetCitiesForAutoComplete method to return all cities. Autocomplete will handle the filtering.

public JsonResult GetCitiesForAutocomplete()
{
    return Json(GetCities(), JsonRequestBehavior.AllowGet);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.