我正在尝试在C#中实现一个简单的WebMethod
以搜索50,000个人的数据库。我正在使用Twitter Bootstrap bloodhound.js
和typeahead.js
标记化并自动完成响应。
当我运行此代码时,typeahead将显示一个带有undefined
的下拉菜单。
如何正确处理JSON响应以剥离.NET d
返回的WebMethod
对象并将记录正确传递给Bloodhound?我已经尝试使用jQuery的dataFilter
提供的$.ajax
方法进行此操作,但是它不适用于我。
C#WebMethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object searchStaffByName(string q)
{
using (App_Data.DQDBDataContext dc = new App_Data.DQDBDataContext())
{
var results = dc.getStaffDetails(q).ToList();
return new { Status = "OK", Records = results, Count = results.Count };
}
}
提前执行JS实现:
var textlookup = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.val);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'Search.aspx/searchStaffByName',
replace: function (url, query) {
searchQuery = query;
return url;
},
ajax: {
beforeSend: function (jqXhr, settings) {
settings.data = JSON.stringify({
q: searchQuery
});
jqXhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
},
dataFilter: function (data, type) {
if (type === "json") {
data = $.parseJSON(data);
if (typeof data.d === 'object' && data.d.Count > 0) {
return data.d.Records;
}
}
},
type: 'POST'
}
}
});
textlookup.initialize();
$('.autocomplete').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'textlookup',
displayKey: 'Forename',
source: textlookup.ttAdapter()
});
样本JSON响应:
{
"d": {
"Status":"OK",
"Records": [{
"id":45711192,
"phone":"514-579-5721",
"Forename":"Jayden",
"Surname":"Adams",
"DOB":"\/Date(990226800000)\/"
},
{
"id":12603644,
"phone":"333-143-9094",
"Forename":"Jake",
"Surname":"Adams",
"DOB":"\/Date(43542000000)\/"
},
{
"id":68196438,
"phone":"440-505-2403",
"Forename":"Josh",
"Surname":"Adams",
"DOB":"\/Date(-51152400000)\/"
}],
"Count":6
}
}
最佳答案
如果您的预输入数据将在name: 'textlookup',
数组中,请首先使用JSON响应填充该数组。以下假设数据是JSON。
textlookup = [];
for (var i = 0; i < data.d.Records.length; i += 1) {
textlookup.push(data.d.Records[i].Forename);
}
这应该将每个
Forename
推入数组textlookup
。由于将对象放置到数组中,因此出现未定义的错误。关于c# - Typeahead.js和Bloodhound.js与C#WebForms WebMethod集成,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25310055/