Here is my JsonResult in my controller:
//
// GET: /Home/GetTags/
public JsonResult GetTags()
{
List<string> Tags = Db.Tags.Select(t => t.Name).ToList();
return Json(Tags, JsonRequestBehavior.AllowGet);
}
Here is what the data looks like if I browse to /Home/GetTags:
["Author","Movie","Video Game","Website","Republican","Democrat"]
Here is the jQuery function in my view:
<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>
Copied the jQuery from jQuery UI website. It was working fine with static data. The JsonResult doesn’t seem to be called at all. When I put a breakpoint in it and debug it, it never hits the breakpoint.
Apparently, the “Custom minLength” was the problem (ie the “search” property of the “autocomplete()” function call. Here’s the revised jQuery:
Also, I revised the JsonResult in the controller like so, to provide only the values that matched what the user typed in the box: