In this article I will explain with an example, how to implement
Bootstrap AutoComplete TextBox using
jQuery TypeAhead plugin in ASP.Net with C# and VB.Net.
The
Bootstrap AutoComplete TextBox will be populated with records from database table using
jQuery AJAX and
WebMethod (
PageMethod) in ASP.Net.
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.
Implementing Bootstrap AutoComplete TextBox using jQuery TypeAhead plugin
HTML Markup
The HTML Markup 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.
The Button has been assigned with an OnClick event handler.
Bootstrap TypeAhead AutoComplete plugin implementation
Inside the HTML Markup, the following
Bootstrap 5
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 event handler, a
jQuery AJAX call is made to the
GetCustomers WebMethod (PageMethod) and the list of customers returned from the
WebMethod (PageMethod) 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.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<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 () {
$('[id*=txtSearch]').typeahead({
minLength: 1,
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Default.aspx/GetCustomers") %>',
data: "{ 'prefix': '" + request + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
items = [];
map = {};
$.each(data.d, function (i, item) {
var id = item.split('-')[1];
var name = item.split('-')[0];
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) {
$('[id*=hfCustomerId]').val(map[item].id);
return item;
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
Enter search term:
<asp:TextBox ID="txtSearch" runat="server" CssClass="form-control" autocomplete="off" Width="300" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="OnSubmit" />
</form>
</body>
</html>
Namespaces
You will need to import the following namespaces.
C#
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
Fetching the records using WebMethod
Inside the
WebMethod, the records from the
Customers Table are matched with the
prefix and are fetched.
The fetched records are processed and a Key Value Pair is created by appending the Id and Name in the following format {0}-{1} where the Name is {0} and {1} is the Id of the Customer.
Finally, the string Array is returned.
C#
[WebMethod]
public static string[] GetCustomers(string prefix)
{
List<string> customers = new List<string>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT ContactName, CustomerId FROM Customers WHERE ContactName LIKE @SearchText + '%'";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@SearchText", prefix);
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
}
}
con.Close();
}
}
return customers.ToArray();
}
VB.Net
<WebMethod>
Public Shared Function GetCustomers(ByVal prefix As String) As String()
Dim customers As List(Of String) = New List(Of String)()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Dim query As String = "SELECT ContactName, CustomerId FROM Customers WHERE ContactName LIKE @SearchText + '%'"
Using cmd As SqlCommand = New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@SearchText", prefix)
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(String.Format("{0}-{1}", sdr("ContactName"), sdr("CustomerId")))
End While
End Using
con.Close()
End Using
End Using
Return customers.ToArray()
End Function
Fetching the selected item on Server Side
When Submit button is clicked, the Key (Customer Name) and Value (Customer ID) are fetched from the Request.Form collection.
Note: Request.Form collection is used, as in some browsers the Text property does not hold the value set from Client Side, when the TextBox is set as ReadOnly.
Finally, the
Name and
Id of the selected customer is displayed using
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnSubmit(object sender, EventArgs e)
{
string customerName = Request.Form[txtSearch.UniqueID];
string customerId = Request.Form[hfCustomerId.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + customerName + "\\nID: " + customerId + "');", true);
}
VB.Net
Protected Sub OnSubmit(sender As Object, e As EventArgs)
Dim customerName As String = Request.Form(txtSearch.UniqueID)
Dim customerId As String = Request.Form(hfCustomerId.UniqueID)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Name: " & customerName & "\nID: " & customerId & "');", True)
End Sub
Screenshot
Demo
Downloads