I am using JQueryUI Autocomplete and am wondering how to use a custom object as my data source (i.e. I want to pass back a list of the following type):
public class Tag
{
public string Name { get; set; }
public int Count { get; set; }
}
The autocomplete code that I am currently using (and that works fine when I pass back a straight forward string array of names) is pretty much a copy off the jQuery UI site:
$(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("Home/GetTag", {
term: extractLast(request.term)
}, response);
},
search: function () {
// custom minLength
var term = extractLast(this.value);
if (term.length < 1) {
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;
}
});
});
The only thing I've changed from the original demo source is the Url and I'm splitting on a space rather than comma (for multiple autocomplete).
Here's the HTML:
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags"/>
</div>
Ideally, I want to present the user with a list of names, with corresponding count alongside.