jQuery Autocomplete + JSON + ASP.NET MVC + key value pair example

Posted by Omri on November 5th, 2009

It took us a while to get this working properly – largely due to some pesky javascript errors but also because we wanted to return a key/value pair. We had a big head start, however, thanks to German Schuager’s article which employs the jQuery Autocomplete plugin and clearly explains how to consume JSON from ASP.NET MVC.

The first problem we encountered was with this line of code:

rows[i] = { data: data[i], value: data[i].EpisodeName,
result: data[i].EpisodeName };

Because originally we put a field of type integer into “value”, like this:

rows[i] = { data: data[i], value: data[i].EpisodeID,
result: data[i].EpisodeName };

A javascript error occurred in autocomplete.js related to if(data[i].result.toLowerCase() == q.toLowerCase(). Presumably the “toLowerCase()” method doesn’t play nicely with non-text types. The reason we were trying to do this in the first place was because we wanted the EpisodeID to be passed through as well as the EpisodeName.

In the end we discovered that there was an even easier way of obtaining the EpisodeID:

$("#episodes").result(function(event, data, formatted) {
if (data)
$(this).parent().next().find("input").val(data["EpisodeID"]);
});

After the user selects an item from the list, “result” is called and by using this notation data["EpisodeID"]  we’re able to retrieve the EpisodeID or any field in the row that is passed in the original JSON response. Once the field is retrieved we place it in a hidden input tag and can do whatever we want with it when the form is submitted.

Download a full working example from here.

Tweet This Tweet This!

Leave a Reply