我试图在我的应用程序中使用Twitter Typeahead.js。但它似乎没有用。我想我在任何地方都缺少一些代码,但无法弄清楚我哪里出错了。
脚本参考
<script src="~/plugins/typeahead/typeahead.bundle.min.js"></script>
HTML
<input type="text" class="form-control typeahead" id="txtRegNo" data-url="@Url.Action("RegistrationNoSearch")">
JS代码
$(function () {
var RegNoSearch = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: $("#txtRegNo").data("url"),
filter: function (datas) {
return $.map(datas.results, function (data) {
return {
value: data.RegNo,
id: data.RegId
};
});
},
ajax: {
type: 'POST',
data: {
param: function () {
return $('#txtRegNo').val();
}
},
context: this
}
}
});
// Initialize the Bloodhound suggestion engine
RegNoSearch.initialize();
$('#txtRegNo .typeahead').typeahead({
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: RegNoSearch.ttAdapter()
});
});
控制器代码
[HttpPost]
public JsonResult RegistrationNoSearch(string regNo)
{
try
{
List<clsRegistrationNoSearch> _lstRegNoSearch = new List<clsRegistrationNoSearch>();
_lstRegNoSearch = _db.StudentRegistrations
.Where(r => r.RegistrationNumber.StartsWith(regNo))
.Select(r => new clsRegistrationNoSearch
{
RegId=r.Id,
RegNo=r.RegistrationNumber
}).ToList();
return Json(_lstRegNoSearch, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(null);
}
}