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.