Question

I am trying to make it work with Web-Api and typeahead.js, i think i am missing something and this code is not working, what i am missing here, here is the complete code i used.

my controller code

public IEnumerable<Songs> GetSongs()
{
    string searchTerm="";
    List<Songs> songList = new List<Songs>();
    songList.Add(new Songs { Name = "Addat", Artist = "Aatif Aslam", Year = "2007" });
    songList.Add(new Songs { Name = "Woh Lamhey", Artist = "Jal - The band", Year = "2008" });
    songList.Add(new Songs { Name = "Kryptonite", Artist = "3 Doors Down", Year = "2009" });
    songList.Add(new Songs { Name = "Manja", Artist = "Amit Trivedi", Year = "2013" });
    songList.Add(new Songs { Name = "Tum hi ho", Artist = "Arjit Singh", Year = "2013" });

    songList = songList.Where(m => m.Name.Contains(searchTerm)).ToList();

    return songList;
}

here is the helper class

public class Songs
{
    public string Name { get; set; }
    public string Year { get; set; }
    public string Artist { get; set; }
}

simple html page with javascript call

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script src="Scripts/typeahead.bundle.min.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
    <link href="Content/typeahead.css" rel="stylesheet" />
    <script type="text/javascript">

        $(document).ready(function () {


            $("#search-box2").typeahead({
                name: 'songs',
                displayKey: 'Name',
                remote: {
                    url: 'http://localhost:8822/api/Search/GetSongs?searchTterm=%QUERY',
                    dataType: 'json'
                }
            });
        });
    </script>
</head>
<body>


    <input type="text" id="search-box2" class="form-control" />
</body>
</html>
Was it helpful?

Solution

This is what you can do :

$(document).ready(function () {
    var songlist = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('songs'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 10,
        remote: 'http://localhost:8822/api/Search/GetSongs?searchTterm=%QUERY'

    });

    // kicks off the loading/processing of `local` and `prefetch`
    songlist.initialize();
    // debugger;

    // passing in `null` for the `options` arguments will result in the default
    // options being used
    $('#search-box2').typeahead(null, {
        name: 'song',
        displayKey: 'Name',
        // `ttAdapter` wraps the suggestion engine in an adapter that
        // is compatible with the typeahead jQuery plugin
        source: songlist.ttAdapter()
    });

});

More Details from documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top