这是我控制器中的JsonResult:
//
// GET: /Home/GetTags/
public JsonResult GetTags()
{
List<string> Tags = Db.Tags.Select(t => t.Name).ToList();
return Json(Tags, JsonRequestBehavior.AllowGet);
}
如果我浏览/ Home / GetTags:
,这是数据的样子["Author","Movie","Video Game","Website","Republican","Democrat"]
以下是我视图中的jQuery函数:
<script type="text/javascript">
$(function() {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#Tags")
// Don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function(request, response) {
$.getJSON("@Url.Action("GetTags")", {
term: extractLast(request.term)
}, response);
},
search: function() {
// Custom minLength
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function() {
// Prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// Remove the current input
terms.pop();
// Add the selected item
terms.push(ui.item.value);
// Add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
从jQuery UI网站复制jQuery。它与静态数据一起工作正常。似乎根本没有调用JsonResult。当我在其中放置一个断点并对其进行调试时,它永远不会遇到断点。
答案 0 :(得分:0)
如何将[HttpGet]
添加到操作之上。所以,它将是:
[HttpGet]
public JsonResult GetTags()
{
List<string> Tags = Db.Tags.Select(t => t.Name).ToList();
return Json(Tags, JsonRequestBehavior.AllowGet);
}
答案 1 :(得分:0)
显然,“自定义minLength”是问题(即“autocomplete()”函数调用的“搜索”属性。这是修订后的jQuery:
<script type="text/javascript">
$(function() {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#Tags")
// Don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function(request, response) {
$.getJSON("@Url.Action("GetTags")", {
term: extractLast(request.term)
}, response);
},
focus: function() {
// Prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// Remove the current input
terms.pop();
// Add the selected item
terms.push(ui.item.value);
// Add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
另外,我修改了控制器中的JsonResult,只提供与用户在框中输入的内容相匹配的值:
//
// GET: /Home/GetTags/
public ActionResult GetTags(string term)
{
List<string> Tags = Db.Tags.Select(t => t.Name).Where(n => n.Contains(term)).ToList();
return Json(Tags, JsonRequestBehavior.AllowGet);
}