Search code examples
c#asp.net-mvckendo-uikendo-autocomplete

Why is my Kendo AutoComplete widget not binding to a JSON object?


I have the following code in an MVC controller:

public JsonResult ARequest()
{
    Dictionary<string, object> AnObject = new Dictionary<string,object>();
    AnObject["foo"] = new object[] {"item 1", "item 2", "item 3"};
    return Json(AnObject, JsonRequestBehavior.AllowGet);
}

And it works as expected; when I call it from a browser, I get the following JSON object:

{"foo":["item 1","item 2","item 3"]}

I have another file, this time with a Kendo UI Autocomplete Widget. Here is the code:

<input id="products" style="width: 250px" />

/*...*/

$("#products").kendoAutoComplete({
   filter: "contains",
   minLength: 3,
   dataTextField: foo,
   dataSource: {
      type: "odata",
      pageSize: 10,
      transport: {
         read: {
            url: "education-portal/ARequest"
         }
      }
   }
});

As per the official examples here and here.

The problem is, when I load the page I don't get anything. The AutoComplete is blank and it stays blank. No results show up when I type anything in the box. Any idea what went wrong? I can't see it for the life of me.


Solution

  • There are several problems:

    • You should not define dataTextField since your array of value are not objects but strings.
    • You should say where in the received data is actually the array of items.
    • Is the type odata or JSON?

    It should be something like:

    $("#products").kendoAutoComplete({
        filter: "contains",
        minLength: 3,
        dataSource: {
            type: "json",
            pageSize: 10,
            transport: {
                read: {
                    url: "education-portal/ARequest"
                },
                schema : {
                    data: "foo"
                }
            }
        }
    });
    

    Example here : http://jsfiddle.net/OnaBai/rSjpS/