Question

I am trying to write my very first jQuery autocomplete example. I need to be able to select multiple values from the autocompletion so I used the example provided here.

No matter what I do I can't get the textbox to display the values "chicken" and "chickens" when I type "c", "ch" etc. What am I doing wrong?

My controller has this action method

public JsonResult GetBirds()
{
    var result = new JsonResult
        {
            Data = new
                {
                    Birds = new List<string> {"chicken", "chickens"}
                },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };

    return result;
}

And my front-end code is this:

<script>
    $(function () {
        function log(message) {
            $("<div/>").text(message).prependTo("#log");
            $("#log").scrollTop(0);
        }

        $("#birds").autocomplete({
            source: "/Results/GetBirds",
            minLength: 1,
            select: function (event, ui) {
                log(ui ?
                "Selected: " + ui :
                "Nothing selected, input was " + this.value);
            }
        });
    });
</script>



<div class="demo">

    <div class="ui-widget">
        <label for="birds">Birds: </label>
        <input id="birds" />
    </div>

    <div class="ui-widget" style="margin-top:2em; font-family:Arial">
        Result:
        <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
    </div>

</div><!-- End demo -->
Was it helpful?

Solution

Use Rest Clint or Firebug Firefox plugin to see what is returning from controller.

Try this:

return Json(new {"chicken", "chickens"},JsonRequestBehavior.AllowGet);

OTHER TIPS


You need to build a dictionary list with "value" and "label" for each object.

http://api.jqueryui.com/autocomplete/

Your source is not in the correct format, forget your "Birds" key in the json result. Just go with:

Data = new List<string> {"chicken", "chickens"}

or

Data = new Dictionary<string, string> {
    {"chiken", "value1"},
    {"chikens", "value2"},
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top