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.
The jQuery Bootstrap AutoComplete TextBox data will be populated from database using Entity Framework in ASP.Net Core (.Net Core 7) Razor Pages.
This article makes use of Bootstrap version 5.
Note: For beginners in ASP.Net Core (.Net Core 7) Razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

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 { getset; }
    public string ContactName { getset; }
}
 
 

Database Context

Once the Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
Note: For beginners in ASP.Net Core Razor Pages and Entity Framework, please refer my article .Net Core 7: Entity Framework Tutorial in ASP.Net Core Razor Pages. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core Razor Pages.
 
using Microsoft.EntityFrameworkCore;
 
namespace Bootstrap_5_AutoComplete_Core_Razor
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<CustomerModel> Customers { getset; }
    }
}
 
 

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{ getset; }
    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
 
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, 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
@model Bootstrap_5_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>
    <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({
                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="btnSubmitvalue="Submit" asp-page-handler="Submit" /> 
        <br />
        <br />
        @Html.Raw(ViewData["Message"])
    </form>
</body>
</html> 
 
 

Screenshot

ASP.Net Core Razor Pages: Bootstrap 5 AutoComplete TextBox using jQuery TypeAhead plugin
 
 

Downloads