In this article I will explain with an example, how to implement
Bootstrap AutoComplete TextBox using
jQuery TypeAhead plugin in ASP.Net Core (.Net Core 8) MVC.
This article makes use of
Bootstrap version 5.
Download TypeAhead Plugin
You will need to download the plugin files from the following location.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Model
The model class consists of following properties.
public class CustomerModel
{
[Key]
public string CustomerID { get; set; }
public string ContactName { get; set; }
}
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using Microsoft.EntityFrameworkCore;
namespace Bootstrap_5_AutoComplete_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<CustomerModel> Customers { get; set; }
}
}
Controller
Inside the Controller, first the private property of DbContext class is created.
Then, the DbContext class is injected into the Constructor (HomeController) using Dependency Injection method and the injected object is assigned to the private property of DbContext class.
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 the jQuery AutoComplete
This Action method accepts a parameter named
prefix. When this method is accessed by the
jQuery AutoComplete plugin, the records of the
Customers Table of the
Northwind database are fetched using the
Entity Framework.
The fetched records are then filtered and returned back to the View as JSON.
Action method for handling POST operation
Inside this Action method, the
CustomerName and
CustomerId of the selected item in
jQuery AutoComplete is set into a
ViewBag object.
public class HomeController : Controller
{
private DBCtx Context { get; set; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AutoComplete(string prefix)
{
var customers = (from customer in this.Context.Customers
where customer.ContactName.StartsWith(prefix)
select new
{
label = customer.ContactName,
val = customer.CustomerID
}).ToList();
return Json(customers);
}
[HttpPost]
public IActionResult Index(string CustomerName, string CustomerId)
{
ViewBag.Message = "CustomerName: " + CustomerName + "<br /> CustomerId: " + CustomerId;
return View();
}
}
View
HTML Markup
Inside the View, the ASP.Net TagHelpers is inherited.
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.
Inside the HTML Form, there is an HTML INPUT TextBox (implemented as AutoComplete), a Hidden Field (for saving the Value part of the Autocomplete Item) and a Submit Button.
Bootstrap TypeAhead AutoComplete plugin implementation
Inside the HTML, the following CSS file is inherited.
1. bootstrap.min.css
Then, the following script files are inherited.
1. jquery.min.js
2. bootstrap.bundle.min.js
3. bootstrap3-typeahead.min.js
The TextBox has been applied with the
Bootstrap jQuery TypeAhead AutoComplete plugin.
The
Bootstrap jQuery TypeAhead AutoComplete plugin has been set with the following porperties and event handlers:
Properties:
minLength – For setting minimum character length needed for suggestions to be rendered. Here it is set to 1.
Events:
source - Inside this event handler, a
jQuery AJAX call is made to the Controller’s
AutoComplete Action method and the list of customers returned acts as source of data to the Bootstrap
jQuery TypeAhead AutoComplete.
The data received from the server is processed inside the
jQuery AJAX call
success event handler. A FOR EACH loop is executed for each received item in the list of items and then an object with text part in the
name property and value part in the
id property is returned.
updater - When an item is selected from the List of the
Bootstrap jQuery TypeAhead AutoComplete, then the
updater event handler is triggered which saves the ID of the selected item in the HiddenField element.
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.2/css/bootstrap.min.css" media="screen" />
<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://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/bassjobsen/Bootstrap-3-Typeahead/master/bootstrap3-typeahead.min.js"></script>
<script type="text/javascript">
$(function () {
$("#txtCustomer").typeahead({
hint: true,
source: function (request, response) {
$.ajax({
type: "POST",
url: '/Home/AutoComplete/',
data: { prefix: request },
success: function (data) {
items = [];
map = {};
$.each(data, function (i, item) {
var id = item.val;
var name = item.label;
map[name] = { id: id, name: name };
items.push(name);
});
response(items);
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
updater: function (item) {
$('#hfCustomer').val(map[item].id);
return item;
}
});
});
</script>
<form method="post" asp-controller="Home" asp-action="Index">
<input type="text" id="txtCustomer" name="CustomerName" class="form-control" autocomplete="off" style="width:300px" />
<input type="hidden" id="hfCustomer" name="CustomerID" />
<br />
<input type="submit" id="btnSubmit" value="Submit" />
<br />
<br />
@Html.Raw(ViewBag.Message)
</form>
</body>
</html>
Screenshot
Downloads