Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Creating an AutoComplete textbox with images for profiles with MVC and jQuery

0.00/5 (No votes)
11 Sep 2013 1  
Creating an AutoComplete with Images for profile with MVC and Jquery

Sometimes we need to create an autocomplete textbox in our projects which contains images of the user, whether its MVC or ASP.NET. jQueryUI has a control for this and you can leverage it to achieve your requirement. All it needs is an array of data. 

Here is the solution for how to do that.

On the View:

<input type="text" id="txtUserSearch" />

<script type="text/javascript">
    $(document).ready(function () {
        $('#txtUserSearch').autocomplete({
            source: '@Url.Action("GetMatchingUser", "Home")',
            minLength: 1,
            select: function (event, ui) {
                window.location.href = 
                  '@Url.Action("ProfilePage", "UserProfile")' + '?who=' + ui.item.id;
            },
            }
        }).data("ui-autocomplete")._renderItem = function (ul, item) {
            var inner_html = 
                 '<a><div class="list_item_container"><div class="image"><img src="' + 
                 item.image + '"></div><div class="label">' + item.label + 
                 '</div><div class="description">' + 
                 item.description + '</div></div></a>';
            return $("<li></li>")
                .data("item.autocomplete", item)
                .append(inner_html)
                .appendTo(ul);
        };
    });
</script>

On the Controller:

public JsonResult GetMatchingUser(string term)
{
    Response.CacheControl = "no-cache";
    YourDBContext DB = new YourDBContext();
    var usrScreenNamelst = DB.Users.Where(a => (a.UserScreenName.StartsWith(term) || 
           a.UserFirstName.StartsWith(term) || a.UserLastName.StartsWith(term))).ToList();
    string userProfileImagePath ="~/Images/";
    var lst = usrScreenNamelst.Select(m => new { id = m.UserId, 
         value = m.UserScreenName, label = m.UserScreenName, 
         description = m.UserFirstName + " " + m.UserLastName, 
         image = Url.Content(userProfileImagePath + (string.IsNullOrEmpty(m.UserImage) ? 
         "NoProfileImage.png" : m.UserImage)) }).ToList().Take(5);
    return Json(lst.ToArray(), JsonRequestBehavior.AllowGet);
}

Using this method you can add Facebook and IMDB like search capabilities in your application. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here