我正在尝试使用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>
答案 0 :(得分:2)
这是你可以做的:
$(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()
});
});