In this article I will explain with an example, how to implement
Bootstrap AutoComplete TextBox using
jQuery TypeAhead plugin in ASP.Net MVC.
This article makes use of
Bootstrap version 5.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Creating an Entity Data Model
The very first step is to create an ASP.Net MVC Application and connect it to the Northwind Database using
Entity Framework.
Following is the Entity Data Model of the Customers Table of the Northwind Database which will be used later in this project.
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 the jQuery AutoComplete
This Action method accepts a parameter named “prefix” and the records from the
Customers Table are matched with the
prefix and 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
This Action method handles the Form submission and displays the
Name and
CustomerId of the selected item in
Bootstrap AutoComplete TextBox using
ViewBag object.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AutoComplete(string prefix)
{
NorthwindEntities entities = new NorthwindEntities();
var customers = (from customer in entities.Customers
where customer.ContactName.StartsWith(prefix)
select new
{
label = customer.ContactName,
val = customer.CustomerID
}).ToList();
return Json(customers);
}
[HttpPost]
public ActionResult Index(string CustomerName, string CustomerId)
{
ViewBag.Message = "CustomerName: " + CustomerName + " CustomerId: " + CustomerId;
return View();
}
}
View
The View consists 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 View also consists of:
TextBox – For capturing Name of the customer.
The TextBox has been assigned with an autocomplete property set to off which is used to prevent unwanted suggestion i.e. manually typed name which is not present in Customers table.
Note: Some browser my ignore autocomplete property or provide different autocomplete suggestion based on their algorithms and user’s browsing history.
HiddenField – For capturing selected CustomerId of the selected customer.
Button – For displaying selected Name and CustomerId of the selected customer.
Implementing TypeAhead Plugin
Inside the HTML, the following
Bootstrap 5 and
TypeAhead CSS files are inherited.
1. bootstrap.min.css
2. typeaheadjs.min.css
And then, the following
jQuery and
Bootstrap TypeAhead JS files are inherited.
1. jquery.min.js
2. bootstrap3-typeahead.min.js
The
Bootstrap jQuery TypeAhead AutoComplete plugin has been applied to the TextBox.
The TextBox has been applied with the following
Bootstrap jQuery TypeAhead AutoComplete plugin:
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 Controller’s
AutoComplete Action method and the list of customers returned which acts as a 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.
Events:
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
CustomerId of the selected item in the ASP.Net HiddenField control.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>ssss
</head>
<body>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js-bootstrap-css/1.2.1/typeaheadjs.min.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://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<script type="text/javascript">
$(function () {
$("#txtCustomer").typeahead({
minLength: 1,
source: function (request, response) {
$.ajax({
url: '/Home/AutoComplete/',
data: "{ 'prefix': '" + request + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
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);
$(".dropdown-menu").css("height", "auto");
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
updater: function (item) {
$('#hfCustomer').val(map[item].id);
return item;
}
});
});
</script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<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 />
@ViewBag.Message
}
</body>
</html>
Screenshot
Demo
Downloads