我正在尝试在标准的mvc应用中实现此web api自动完成功能。 http://techbrij.com/987/jquery-ui-autocomplete-asp-net-web-api
这是Firebug http://sdrv.ms/N0WkHP的屏幕抓取
我已经创建了一个控制器方法并添加了jquery脚本,但我一直收到'JSON.parse:意外字符'错误。我的数据中没有看到任何异常字符。
$(document).ready(function () {
$('#txtSearch3').autocomplete({
source: function (request, response) {
$.ajax({
url: '/home/Get',
type: 'GET',
cache: false,
data: request,
dataType: 'json',
success: function (json) {
// call autocomplete callback method with results
response($.map(json, function (name, val) {
return {
label: name,
value: val
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error - ' + textStatus);
console.log('error', textStatus, errorThrown);
}
});
},
minLength: 2,
select: function (event, ui) {
alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
$('#txtSearch3').val(ui.item.label);
return false;
}
})
});
//我的控制器代码
public IDictionary<int, string> Get(string term)
{
using (myEntities context = new myEntities())
{
return context.Categories1.Where(x => x.CategoryName.Contains(term)).ToDictionary(x => x.CategoryId, x => x.CategoryName);
}
}
答案 0 :(得分:0)
尝试让控制器返回JSON。
public JsonResult Get(string term)
{
using (myEntities context = new myEntities())
{
return Json(context.Categories1.Where(x => x.CategoryName.Contains(term)).ToDictionary(x => x.CategoryId, x => x.CategoryName));
}
}
答案 1 :(得分:0)
好的,终于想通了,我的回报应该是我的有效json,不需要标签/值。
感谢您提供的有用回复
$(document).ready(function () {
$('#txtSearch3').autocomplete({
source: function (request, response) {
$.ajax({
url: '/home/Get',
type: 'GET',
cache: false,
contentType: "application/json; charset=utf-8",
data: request,
dataType: 'json',
success: function (json) {
response($.map(json, function () {
return json;
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error - ' + textStatus);
console.log('error', textStatus, errorThrown);
}
});
},
minLength: 2,
select: function (event, ui) {
alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
$('#txtSearch3').val(ui.item.label);
return false;
}
})
});