In this article I will explain with an example, how to implement
jQuery AutoComplete TextBox with Images in ASP.Net Core MVC (.Net Core).
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Image
The Images for the
jQuery AutoComplete TextBox will be saved in the
photos Folder (Directory) of
wwwroot Folder (Directory).
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using jQuery_Image_Autocomplete_Core.Models;
using Microsoft.EntityFrameworkCore;
namespace jQuery_Image_Autocomplete_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
Model
The Model class consists of following properties.
public class Employee
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
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 Employee table using Database Context 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
ViewBag object and the View is returned.
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AutoComplete(string prefixText)
{
var employees = (from employee in this.Context.Employees
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 IActionResult Index(string name)
{
ViewBag.Message = name;
return View();
}
}
View
HTML Markup
The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View also consists of a 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.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<input type="text" id="txtSearch" name="name" />
<input type="submit" value="Submit" />
</form>
<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({
type: "POST",
url: '/Home/AutoComplete/',
data: { "prefixText": request.term },
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