0

I'm using the JQuery Autocomplete Plugin in my Asp.net MVC project. So far, I return a List of Strings from my search method and these strings are displayed correctly.

In my View:

<script type="text/javascript">
    $(function () {
        $("#search").autocomplete({
            source: '<%: Url.Action("Search") %>',
            minLength: 1
        });
    });
</script>

Controller:

public JsonResult Search(string term)
{
  //search Code here ...  
  var dt = ....;
  var result = new List<string>();
  //search Code returns a DataTable, which I convert into a List<string>

    for (int i = 0; i < dt.Rows.Count; i++)
    {
      result.Add(...);
    }

  //return List<string> to the autocomplete plugin
  return Json(result, JsonRequestBehavior.AllowGet);
}

I wonder if it's possible to return a DataTable object and display the DataTable in a HTML table. Or is it possible to return a HTML table? Has anyone tried something like this?

Thanks a lot

Jaspis

2 Answers 2

1

Step 1 : Getting Web Api Ready

Lets first create a web api method that will return a list of item (Artists) using the search term query sent from the autocomplete textbox. In this post I am not using database, instead I'll be using List to keep this example as simple as possible.

Below is how I have defined my Artist class

public class Artist
{
    public int Id { get; set; }
    public int Name { get; set; }
}    

Next I have created a Web Api GET method that will use the search term entered in the autocomplete textbox and with a little help of LINQ will return a list of matching results.

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Autocomplete.Controllers
{
    public class ArtistApiController : ApiController
    {

        public List<Artist> ArtistList = new List<Artist>
        {
            new Artist{Id = 1, Name = "Sonu Nigam"},
            new Artist{Id = 2, Name = "Sunidhi Chauhan"},
            new Artist{Id = 3, Name = "Shreya Goshal"},
            new Artist{Id = 4, Name = "Mohit Chauhan"},
            new Artist{Id = 5, Name = "Nihkil Dsouza"},
            new Artist{Id = 6, Name = "Kailash Kher"},
            new Artist{Id = 7, Name = "Atif Aslam"},
            new Artist{Id = 8, Name = "Ali Zafar"},
            new Artist{Id = 9, Name = "Shafaqat Ali"},
            new Artist{Id = 10, Name = "Shankar Madahevan"}
        }; 


        // GET api/values
        public IEnumerable<Artist> Get(string query)
        {
            return ArtistList.Where(m => m.Name.Contains(query)).ToList();
        }
    }
}   

Our server side code is ready ! Time to test it out.

enter image description here

Step 2 : Client side code

Include jquery-ui.js and jquery.ui.css in your html

<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.8.20.min.js" ></script>
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />

<div id="body">
    <label for="autocomplete-textbox">Search : </label>
    <input type="text" id="autocomplete-textbox" />
</div>

<script type="text/javascript">
$(document).ready(function (){
$('#autocomplete-textbox').autocomplete({
    source: function (request, response) {
        // prepare url : for example '/api/artistapi?query=sonu
        var autocompleteUrl = '/api/artistapi' + '?query=' + request.term;
        $.ajax({
            url: autocompleteUrl,
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function (json) {
                // call autocomplete callback method with results  
                response($.map(json, function (data, id) {
                    return {
                        label: data.Name,
                        value: data.Id
                    };
                }));
            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                console.log('some error occured', textStatus, errorThrown);
            }
        });
    },
    minLength: 2,
    select: function (event, ui) {
        alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
        $('#autocomplete-textbox').val(ui.item.label);
        return false;
    }
});
});
</script>

One thing to note here is that inside the success method I have used the following code :

response($.map(json, function (data, id) {
    return {
        label: data.Name,
        value: data.Id
    };
}));

data.Id and data.Name is used because in the ajax response (as shown below) data is returned in this format.

enter image description here

Step 3 : Test & Output :

enter image description here

Taken from here

Sign up to request clarification or add additional context in comments.

Comments

0

You may take a look at the custom data and display sample.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.