【问题标题】:Using Typeahead.js with ASP.NET WebAPI将 Typeahead.js 与 ASP.NET WebAPI 一起使用
【发布时间】:2014-07-30 04:55:27
【问题描述】:

我正在尝试使其与 Web-Api 和 typeahead.js 一起使用,我想我遗漏了一些东西并且这段代码不起作用,我在这里遗漏了什么,这是我使用的完整代码。

我的控制器代码

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;
}

这里是辅助类

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

带有javascript调用的简单html页面

<!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>

【问题讨论】:

    标签: asp.net typeahead.js


    【解决方案1】:

    这是你可以做的:

    $(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

    【讨论】:

    最近更新 更多