ASP.Net MVC: Creating an AutoComplete with Images for profile with MVC and Jquery

Sometime we need to create a autocomplete textbox in our projects, whihc containes images of the user. whether its MVc or Asp.net. JqueryUI have a control for this and you can leverage to make your wish fullfil. its need a Array of data. Here is the solution how to do that.
You need to take the reference of the latest jqueryui script.
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);
        }

Comments

Popular posts from this blog

LINQ: Using int.TryParse() within a LINQ where clause

ASP.Net MVC: Configuring asp.net session state in SQL Server.

IIS: Publish Project to remote IIS with Web Deploy.