In this article I will explain with an example, how to implement
jQuery AutoComplete TextBox with Images in ASP.Net Core (.Net Core 7) Razor Pages.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Image File
The Image will be saved in the photos Folder (Directory) of wwwroot 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_Razor.Models;
using Microsoft.EntityFrameworkCore;
namespace jQuery_Image_Autocomplete_Core_Razor
{
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; }
}
Razor PageModel (Code-Behind)
The PageModel consists of following Handler methods.
Handler method for handling GET operation
This Handler method is left empty as it is not required.
Handler method for handling jQuery AJAX operation
This Handler method handles the call made from the
jQuery AJAX function from the View.
Note: The following Handler method handles
AJAX calls and hence the return type is set to
JsonResult.
This Handler method accepts
jQuery AutoComplete TextBox value as a parameter.
Inside this Handler 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.
Handler method for handling POST operation
This Handler method accepts selected
AutoComplete Item (Employee Name) as parameter which is later set into
ViewData object.
public class IndexModel : PageModel
{
private DBCtx Context { get; }
public IndexModel(DBCtx _context)
{
this.Context = _context;
}
public void OnGet()
{
}
public IActionResult OnPostAutoComplete(string prefixText)
{
var employees = (from employee in this.Context.Employees
where employee.FirstName.StartsWith(prefixText)
select new
{
label = string.Format("{0} {1}", employee.FirstName, employee.LastName),
val = string.Format("/photos/{0}.jpg", employee.EmployeeID)
}).ToList();
return new JsonResult(employees);
}
public void OnPostSubmit(string name)
{
ViewData["Messsage"] = name;
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The HTML of Razor Page consists of a HTML INPUT TextBox and a Submit Button.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
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
AntiForgery Token has been added to the Razor Page using the
AntiForgeryToken function of the HTML Helper class.
The URL for the
jQuery AJAX call is set to the Controller’s action method i.e. /Index?handler=AutoComplete.
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 Handler 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
ViewData object is checked for NULL and if it is not NULL then, the value of the
ViewData object is displayed using
JavaScript Alert Message Box.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model jQuery_Image_Autocomplete_Core_Razor.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
@Html.AntiForgeryToken()
<input type="text" id="txtSearch" name="name" />
<input type="submit" value="Submit" asp-page-handler="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: '/Index?handler=AutoComplete',
data: { "prefixText": request.term },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
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 (ViewData["Messsage"] != null)
{
<script type="text/javascript">
$(function () {
alert('@ViewData["Messsage"]');
});
</script>
}
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads