我需要创建一个 jQuery 自动完成文本框,从数据库中获取姓名列表,并在选择时将用户发送到相应的页面链接。
我正在尝试像这篇文章一样做一些事情:Fire a controller action from a jQuery Autocomplete selection
该解决方案很有意义,点击和重定向有效,但我不知道如何返回更多的名称字符串列表。
当前 Controller 代码(片段):
List<string> Names = new List<string>();
foreach (Child c in listfromDB)
{
Names.Add(c.Name);
//childNames.Add(new KeyValuePair<string, int>(c.Name, c.ID));
}
return Json(Names);
KeyValuePair
似乎不起作用。我该如何创建一个对象数组呢?
我的 jQuery 代码:
$(document).ready(function () {
$("#find-child-box").autocomplete({
source: function (request, response) {
// define a function to call your Action (assuming UserController)
$.ajax({
url: '/Admin/AutoCompleteMyChildren', type: "POST", dataType: "json",
// query will be the param used by your action method
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item, value: item };
}))
}
})
},
minLength: 1, // require at least one character from the user
select: function(event, ui) {
alert('mom');
window.location.href = ui.item.value;
}
});
});
最佳答案
实际上,自动完成可以很好地处理仅返回字符串数组的源。这对您来说应该可以正常工作,而无需修改您的 Controller 操作:
JavaScript:
$(document).ready(function () {
$("#find-child-box").autocomplete({
source: function (request, response) {
// define a function to call your Action (assuming UserController)
$.ajax({
url: '/Admin/AutoCompleteMyChildren',
type: "POST",
dataType: "json",
// query will be the param used by your action method
data: { query: request.term },
success: response
});
},
minLength: 1, // require at least one character from the user
select: function(event, ui) {
alert(ui.item.ID);
window.location.href = ui.item.value;
}
});
});
检查 overview tab of jQueryUI autocomplete查看小部件需要什么样的数据。
根据您的评论:
正如@Alex 所暗示的那样,您必须更改 Controller 操作的数据。您可以使用类似以下内容创建正确的对象数组:
return Json(listfromDB.Select(c => new { label = c.Name, ID = c.ID }));
应该生成如下所示的 JSON:
[{ label: 'Scott', ID: '1234' }, ...]
哪个自动完成可以正确使用。然后,任何时候 ui.item
在自动完成的事件处理程序中可用(例如 select
),您应该能够访问 ui.item.ID
.
关于c# - 如何从 jQuery 自动完成的 C# Controller 操作返回 Json 标签/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12631245/