Advanced Auto-Complete with jQuery, MVC, and thumbnail pictures

Filed in ASP.NET MVC | C# | jquery 1 Comment

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\">&nbsp;" + 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:

Download Sample Application

Below is a video clip of the sample in action:

, , , ,

Autocomplete using Html, JSON, MVC, jQuery

Filed in ASP.NET MVC | C# | jquery 6 Comments

I found an awesome AutoComplete tutorial (here: http://www.nodstrum.com/2007/09/19/autocompleter/#comment) using PHP, jQuery, MySQL, and decided to port it over to Microsoft’s ASP.NET MVC. Turned out to be way easier than I thought! You can download the auto-complete code sample here.

Configure MVC Controller

So this is basic: create a JsonResult method in your controller that runs a query. I’m using nHibernate and ActiveRecord to perform a top 10 query as you can see here:

public JsonResult GetCountry(string searchString)
{
StringBuilder sb = new StringBuilder();
ICriterion[] query = { Expression.Eq("Code", "COUNTRYLIST"), Expression.Like("Value",searchString, MatchMode.Start) };
LookupCode[] countries = LookupCode.SlicedFindAll(0, 10, query);
for (int i = 0; i < countries.Length; i++)
{
sb.Append("<li onClick=\"fill('" + countries[i].Value + "');\">" + countries[i].Description + "</li>");
}
return Json(sb.ToString());
}

Create jQuery Function

There are two jQuery functions we need. The first function simply calls the GetCountry method:

function lookup(inputString) {
$.post("/LookupCode/GetCountry", { searchString: "" + inputString + ""},
function(data) {
var myObject = eval('(' + data + ')');
if (data.length > 0) {
$("#suggestions").show();
$( "#autoSuggestionsList").html('<ul>' + myObject + '</ul>');
}
});
}

The second method is called from the auto-suggest list, and its job is to populate the selected value into the form field and to hide the auto-suggest list:

function fill(thisValue) {
$("#Country").val(thisValue);
setTimeout("$("#suggestions").hide();", 200);
}

Prep Textbox

There are two things we need to do to configure the textbox to trigger the auto-complete functionality:

1. Add the onkeyup=”lookup(this.value);” attribute within the input:

<input type="text" name="Country" id="Country"  onkeyup="lookup(this.value);"  />

2. Add a DIV to hold the suggestion list:

<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>

That’s it! For extra credit, we can add some style in the next step.

Add Style

The following style was taken and modified from the original tutorial (here: http://www.nodstrum.com/2007/09/19/autocompleter/#comment) , and is really easy to customize:

.suggestionsBox {
position: relative;
left: 5px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #e4e4e4;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #336699;
color:#333333;
}

.suggestionList {
margin: 0px;
padding: 0px;
}

.suggestionList ul {
margin: 0px;
padding: 0px;
}

.suggestionList li {
list-style-type: none;
margin: 0px 0px 0px 0px;
padding: 3px;
cursor: pointer;
}

.suggestionList li:hover {
list-style-type: none;
color:White;
background-color: #336699;
}
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 106px; width: 1px; height: 1px;">function lookup(inputString,prefix) {
if (inputString.length == 0) {
$('#suggestions').hide();
} else {
$.post("/LookupCode/GetCountry", { id: "" + inputString + "", prefix: prefix },
function(data) {

var myObject = eval('(' + data + ')');
var suggestlist = "#" + prefix + "autoSuggestionsList";
var suggestfield = "#" + prefix + "suggestions";

if (data.length > 0) {

$(suggestfield).show();
$(suggestlist).html('<ul>' + myObject + '</ul>');
}
});
}
}
</div>

, , , , , ,

TOP