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 3.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Bootstrap AutoComplete TextBox using jQuery TypeAhead plugin implementation
<link rel="Stylesheet" href="https://twitter.github.io/typeahead.js/css/examples.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/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/3.0.3/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/3.1.1/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>
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 3 CSS files are inherited.
1. examples.css
2. bootstrap.min.css
And then, the following
Bootstrap 3 JS files are inherited.
1. jquery.min.js
2. bootstrap.min.js
3. 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.
Events:
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) 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
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://twitter.github.io/typeahead.js/css/examples.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/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/3.0.3/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/3.1.1/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