In this article I will explain with an example, how to implement
jQuery AutoComplete TextBox with Images in ASP.Net MVC.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Images
The Image for the
jQuery AutoComplete TextBox will be saved in the
photos Folder (Directory) of ASP.Net MVC Project.
Entity Framework Model
Once the
Entity Framework is configured and connected to the database table, the Model will look as shown below.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling jQuery AJAX operation
This Action method handles the call made from the
jQuery AJAX function from the View.
Note: The following Action method handles
AJAX calls and hence the return type is set to
JsonResult.
This Action method accepts
jQuery AutoComplete TextBox value as a parameter.
Inside this Action method, the records are fetched from the
Employees table using
Entity Framework where an object is created with following two properties:
label – For storing name of the employees.
val – For storing path of the image file.
Finally, the List of employees is returned as a
JSON object.
Action method for handling POST operation
This Action method accepts selected
AutoComplete Item (Employee Name) as parameter which is later set into a
ViewBag object and the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AutoComplete(string prefixText)
{
NorthwindEntities entities = new NorthwindEntities();
var employees = (from employee in entities.Employees.AsEnumerable()
where employee.FirstName.ToLower().StartsWith(prefixText.ToLower())
select new
{
label = string.Format("{0} {1}", employee.FirstName, employee.LastName),
val = string.Format("/photos/{0}.jpg", employee.EmployeeID)
}).ToList();
return Json(employees);
}
[HttpPost]
public ActionResult Index(string name)
{
ViewBag.Message = name;
return View();
}
}
View
HTML Markup
The View consist of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of an HTML INPUT TextBox and a Submit Button.
Implementing AutoComplete Plugin with Images
Inside the HTML, the following CSS file is inherited.
1. jquery-ui.css
And then, the following Scripts files are inherited.
1. jquery.min.js
2. jquery-ui.js
Inside the
jQuery document ready event handler, the
jQuery AutoComplete plugin has been applied to the TextBox.
The
jQuery AutoComplete plugin has been assigned with the following properties and functions.
Properties:
minLength – For setting minimum character length needed for suggestions to be rendered. Here it is set to 1.
Functions:
source – Inside this function, a
jQuery AJAX call is made to the
AutoComplete Action method and the returned list of employees acts as a source of data to the
jQuery AutoComplete.
The data received from the server is processed inside the
jQuery AJAX call
Success event handler and Name of the employee and the path of the Image file are set into
label and
value properties respectively.
create – Inside the function, the
jQuery AutoComplete plugin has been assigned with a
renderItem function, inside which an HTML i.e. Unordered List (UL) is generated.
The HTML consists of two DIVs, one for displaying the Employee Name and other for displaying the Image.
Note: The Employee Name is set with the value the label property and the src attribute of the Image element is set with the value property.
Finally, the generated Unordered List is assigned to the LI tag which is ultimately returned.
Submitting the Form
When the
Submit Button is clicked then, the
ViewBag object is checked for NULL and if it is not NULL then, the value of the
ViewBag object is displayed using
JavaScript Alert Message Box.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<input type="text" id="txtSearch" name="name" />
<input type="submit" id="btnSubmit" value="Submit" />
}
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Home/AutoComplete/',
data: "{'prefixText': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1,
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
var items = $('<div class="container">'
+ '<div class="item"><img class="image" src="' + item.val + '" /></div>'
+ '<div class="item"> ' + item.label + '</div><br /><br />'
+ '</div>');
return $("<li>").append(items).appendTo(ul);
}
}
});
});
</script>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
$(function () {
alert('@ViewBag.Message');
});
</script>
}
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads