RawMVC RawMVC - 1 month ago 9
C# Question

ASP.NET MVC: jQuery UI Autocomplete not working correct (always shows all entries)

I read this thread and studied the mistakes and the example that should work. After that I tried to build it on my own, autcomplete works, but it always shows all entries instead of only that entries that match with the search in the database.

So here is controller code that returns the data for my autocomplete function:

public JsonResult AutoCompleteCustomer(string suggestion)
{
var data = db.Customers.Where(s => suggestion == null || s.Name.ToLower().Contains(suggestion.ToLower())).Select(x => new { id = x.CustomerID, value = x.CustomerName }).Take(20).ToList();

return Json(data, JsonRequestBehavior.AllowGet);
}


My code for the autocomplete jQuery UI Feature:

<script>
$("#CustomerName").autocomplete({
source: "/Customer/AutoCompleteCustomer",
minLength: 3
})
</script>


The TextBox in the view that should have autocomplete:

@Html.TextBoxFor(m => m.CustomerName)


If you need any more code or information, please let me know and I will provide it as soon as possible. Thanks!

CSL CSL
Answer

Your controller action has the wrong parameter name it, should be term:

public JsonResult AutoCompleteCustomer(string term)
    {
        var data = db.Customers.Where(s => term== null || s.Name.ToLower().Contains(term.ToLower())).Select(x => new { id = x.CustomerID, value = x.CustomerName }).Take(20).ToList();

        return Json(data, JsonRequestBehavior.AllowGet);
    }

Because it is incorrect at the moment it will always be NULL which is why your autocomplete is working but always returning all results as this criteria suggestion == null is always true.

If you really wanted to stick with suggestion as your controller parameter, you would need to explicitly define this in the AJAX configuration:

<script>
    $("#CustomerName").autocomplete({
        source: "/Customer/AutoCompleteCustomer",
        data: { suggestion: request.term },
        minLength: 3
    })
</script>