I am using a WebApi controller to return an IDictionary to jQuery autocomplete like so:
public IDictionary<int, string> GetClientAuto(string term)
{
var clients = db.Clients.Where(n => n.Name.Contains(term)).OrderBy(n => n.Name);
return clients.ToDictionary(n => n.ClientID, n => n.Name);
}
The issue is although I add a breakpoint and check the variable clients is sorting by Name turns to to be true, the order shown in the autocomplete box is different, possibly I expect by the ID. I tried adding this to the autocomplete: sortResults:false, but with no effect.
I have this in my succes function, is there something here maybe I need to change for the order to work on the label i.e. Name:
success: function (json) {
// call autocomplete callback method with results
response($.map(json, function (name, val) {
return {
label: name,
value: val
}
}));
},
Its being sorted by the ToDictionary call, the order of dictionaries isn’t actually defined (http://msdn.microsoft.com/en-us/library/yt2fy5zk.aspx) as it shouldn’t matter, however i believe it is typically the value of the key, not the value.
You could resort it in javascript to be by name, or you could return something other than a dictionary from your api. Either a IEnumerable> or IEnumerable would do the trick.
Alterntively look into the OrderBy methods on the dictionary, however they all appear to return a list of KeyValuePairs.
End result should look something like