Marcus Marcus - 4 months ago 10
Javascript Question

Creating an autocomplete in ASP.NET MVC error

I am trying to create an autocomplete textbox in ASP.NET MVC using jquery autocomplete.

This is my Index.cshtml:

<div class="autocomplete">
@Html.TextBox("item", null, new { id = "autocomplete-textbox", @class = "form-control" });
<input type="submit" value="Submit" id="autocomplete-button"/>
</div>

<script>
$(function() {
$('#autocomplete-textbox').autocomplete({
source: '@Url.Action("AutoComplete")',
minlength: 1
});
});
</script>


And this is my home controller method:

public JsonResult AutoComplete(string item)
{

IEnumerable<string> itemsList = new[] { "Ana", "are", "mere", "pere", "papaia", "Aaa", "Ab", "An" };
IEnumerable<string> filteredResults = null;

if (string.IsNullOrEmpty(item))
{
filteredResults = itemsList;
}
else
{
filteredResults = itemsList.Where(s => s.IndexOf(item, StringComparison.InvariantCultureIgnoreCase) >= 0);
}

return Json(filteredResults, JsonRequestBehavior.AllowGet);
}


My problem is that the parameter item in the JsonResult AutoComplete is always null and so I always get as a JSON response the whole list. What can I do ?

Thanks,
Marcus

Answer

By default, the jQuery auto complete plugin will send the typed in value with a query string param called term, not item(You can see this if you open up your browsers dev tools-> network tab) .

So change your server action method parameter name to term

public JsonResult AutoComplete(string term)
{
  // use term for your checkings
  // to do : Return something    
}

Also, i noticed another issue in your code. If the term variable is not empty, you need to set the filtered results (The result of your Where method call) to the filteredResults variable because that it what you are returning.

if (string.IsNullOrEmpty(term))
{
    filteredResults = itemsList;
}
else
{
    filteredResults = itemsList
             .Where(s => s.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0);
}