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 7) Razor Pages.
This article makes use of
Bootstrap version 4.
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_4_AutoComplete_Core_Razor
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<CustomerModel> Customers { get; set; }
}
}
Index PageModel (Code-Behind)
Inside the PageModel, first the private property of DbContext class is created.
Then, the DbContext class is injected into the Constructor (P) using Dependency Injection method and the injected object is assigned to the private property of DbContext class.
The PageModel consists of following Handler methods.
Handler method for handling GET operation
This Handler method left empty as it is not required.
Handler method for handling the jQuery AutoComplete
Attribute
ValidateAntiForgeryToken – The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
This Handler 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 as JSON object.
Handler method for handling POST operation
Inside this Handler method, the
CustomerName and
CustomerId of the selected item in
jQuery AutoComplete is set into a
ViewData object.
public class IndexModel : PageModel
{
private DBCtx Context { get; set; }
public IndexModel(DBCtx _context)
{
this.Context = _context;
}
public void OnGet()
{
}
[ValidateAntiForgeryToken]
public JsonResult OnPostAutoComplete(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 new JsonResult(customers);
}
public void OnPostSubmit(string CustomerName, string CustomerId)
{
ViewData["Message"] = "CustomerName: " + CustomerName + "<br /> CustomerId: " + CustomerId;
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, the ASP.Net TagHelpers is inherited and the Anti-Forgery Token has been added to Razor Page using the AntiForgeryToken function of the HTML Helper class.
The HTML Markup of the Razor Page consists of an HTML Form.
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.
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.
Bootstrap TypeAhead AutoComplete plugin implementation
Inside the HTML, the following CSS files are inherited.
1. bootstrap.min.css
2. typeaheadjs.min.css
Then, the following script files are inherited.
1. jquery.min.js
2. 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, the TextBox value i.e.
prefix is passed as parameter to
AutoComplete Handler method using
jQuery AJAX and URL of the Handler method is specified as
/Index?handler=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.
@page
@modelBootstrap_4_AutoComplete_Core_Razor.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<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>
<link rel="Stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.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">
$(function () {
$("#txtCustomer").typeahead({
minLength: 1,
source: function (request, response) {
var token = $('input:hidden[name="__RequestVerificationToken"]').val();
$.ajax({
type: "POST",
url: '/Index?handler=AutoComplete',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", token);
},
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>
@Html.AntiForgeryToken()
<form method="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" asp-page-handler="Submit" />
<br />
<br />
@Html.Raw(ViewData["Message"])
</form>
</body>
</html>
Screenshot
Downloads