sebvst
sebvst

Reputation: 753

ASP.NET: How to get from Dropdownlist to Autocomplete

I have a dropdownlist and want to turn it into autocomplete using jquery.

The dropdown looks like this and works:

@Html.DropDownListFor(m => m.CategoryID, new SelectList(Model.Categories, "ID", "Name", Model.CategoryID), "Categories", new { @class = "form-control" })

I also added an autocomplete field using jquery that works. But so far I can only populate it with dummy data:

$(function () {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp"
    ];

    $("#tags").autocomplete({
        source: availableTags 
    });
});

How can I populate my dropdown field with the data that is available in the dropdown?

Thank you in advance!

Upvotes: 1

Views: 6781

Answers (1)

Shyju
Shyju

Reputation: 218722

You need to set the source as an action method which returns data you want to show as autocomplete option in JSON format.

$(function(){

    $("#tags" ).autocomplete({
      source: "@Url.Action("SearchCategories","Home")",
      minLength: 1,
      select: function (event, ui) {

        //If you want to do something on the select event, you may do it here
        //$("#tags").html(ui.item.label);
      }
    });

})

Make sure you have an action method called SearchCategories in your HomeController which returns the data you want.

public ActionResult SearchCategories(string term)
{
    var db= new MyDbContext();
    var results = db.Categories.Where(s => s.Name.StartsWith(term))
                                       .Select(x=>new {  id =x.Id, 
                                                         label =x.Name }).ToList();
    return Json(results,JsonRequestBehavior.AllowGet);
}

This should enable the autocomplete on an input with id tags,assuming you have jQuery ui library(and it's dependencies) loaded properly in your page and you do not have any other script errors in your page. I have used Url.Action helper method to generate the correct relative url to the action method. It will work fine if your js code is inside a razor view. But if your code is inside an external js file, you should follow the approach described in this post.

Upvotes: 2

Related Questions