This post extends an earlier post I wrote for a basic auto complete/auto suggest textbox.
In this version, we are going to return a list of our favorite social media websites, by adding a new method to the prior post’s controller which allows thumbnail pictures to appear in the auto-suggest list.
New MVC Controller Method
We are going to create another JsonResult method in the controller to lookup the websites. For demo purposes, we are going to hardcode the list. In real life, you probably will be pulling the list from a database, which is covered in the earlier post.
public JsonResult GetWebsites(string searchString)
{
StringBuilder sb = new StringBuilder();
//
// Creating a static list here for demo purposes. In your system, you probably
// will have images generated from the database, disk, flickr, etc.
//
List<string> sites = new List<string>();
sites.Add("Blogger");
sites.Add("Delicious");
sites.Add("Digg");
sites.Add("Facebook");
sites.Add("Flickr");
sites.Add("FriendFeed");
sites.Add("Friendster");
sites.Add("LinkedIn");
sites.Add("MySpace");
sites.Add("StumbleUpon");
sites.Add("Technorati");
sites.Add("Twitter");
sites.Add("Yahoo");
sites.Add("Yelp");
sites.Add("YouTube");
for (int i = 0; i < sites.Count; i++)
{
if (sites[i].ToLower().StartsWith(searchString.ToLower()))
{
string ImageUrl = "/images/" + sites[i].ToString() + ".png";
sb.Append("<li onClick=\"fill('" + sites[i].ToString() + "');\"><img src=\"" + ImageUrl + "\" border=\"0\"> " + sites[i].ToString() + "</li>");
}
}
return Json(sb.ToString());
}
The big addition is adding the <img> tag into the list item value, that’s it :-) Now for tweaking the jquery function from the orinigal post to call the new method:
function lookup(inputString) {
$.post(“/LookupCode/GetWebsites”, { searchString: “” + inputString + “”},
function(data) {
var myObject = eval(‘(‘ + data + ‘)’);
if (data.length > 0) {
$(“#suggestions”).show();
$( “#autoSuggestionsList”).html(‘<ul>’ + myObject + ‘</ul>’);
}
});
}
You can download the fully-function code project here:
Below is a video clip of the sample in action:
