Thursday, February 8, 2018

ASP.NET Core jquery Autocomplete returns blank lines in the list

Leave a Comment

I am using ASP.NET Core jquery Autocomplete with Boostrap 4 I have successfully run the following example from : https://jqueryui.com/autocomplete/

I am now looking to use data from my controller which returns data properly. The result that I get is blank lines.

enter image description here

Here is my Razor page

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  <div class="ui-widget">     <label>Autocomplete Example: </label>     <input id="LastName" name="LastName" type="text" /> </div> <script>     $("#LastName").autocomplete({         source: '@Url.Action("GetName","Home")'     }); </script> 

Here's my controller [HttpGet] public IActionResult GetName(string term) {

        List<TransactionName> list = new List<TransactionName>()         {              new TransactionName {Id=1,LastName="Linda" },             new TransactionName {Id=2,LastName="Donna" },             new TransactionName {Id=3,LastName="Maryanne" },             new TransactionName {Id=4,LastName="Deb" },             new TransactionName {Id=5,LastName="Liz" },             new TransactionName {Id=6,LastName="Bobby" },             new TransactionName {Id=7,LastName="Beth" }      };         var result = (from N in list                         where N.LastName.Contains(term)                         select new {N.LastName });         return Json(result);     } 

enter image description here

2 Answers

Answers 1

I changed the following based on the jquery Autocomplete documentation:

    var result = (from N in list                     where N.LastName.Contains(term)                     select new {value=N.LastName }); 

Here's a portion of the documentation taken from their site. Multiple types supported: Array: An array can be used for local data. There are two supported formats: An array of strings: [ "Choice1", "Choice2" ] An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

Answers 2

Your result is returning to your browser as:

{     "Linda",     "Donna",     //... etc } 

What you actually want to return is:

[     "Linda",     "Donna",     //... etc ] 

To do this, simply change your return line to this:

return Json(result.ToArray());

If this does not work, use browser developer tools to inspect your returned result and modify your return line to format the output as the autocomplete method requires.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment