In this article I will explain with an example, how to use
jQuery AutoComplete in ASP.Net using C# and VB.Net.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of:
TextBox – For capturing Name of the customer.
Button – For displaying selected customer
Name and
CustomerId in
JavaScript Alert Message Box.
HiddenField – For capturing selected customer Name from the TextBox.
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="OnSubmit" />
<asp:HiddenField runat="server" ID="hfCustomerId" />
jQuery AutoComplete Plugin implementation
Inside the HTML, the following
jQuery UI CSS file is inherited.
1. jquery-ui.css
And then, the following
jQuery and
jQuery UI JS files are inherited.
1. jquery.min.js
2. jquery-ui.min.js
Inside the
jQuery document ready event handler, the TextBox has been applied with the
jQuery AutoComplete plugin.
A
jQuery AJAX POST call is made to the
WebMethod and the returned list of
Customers acts as a source of data to the
jQuery AutoComplete.
A
Select event handler has been defined for the
jQuery AutoComplete and items are selected from the
AutoComplete List.
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.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://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("[id*= txtName]").autocomplete({
source: function (request, response) {
var prefix = request.term.toLowerCase();
$.ajax({
url: 'Default.aspx/GetCustomers',
data: "{'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id*= hfCustomerId]").val(i.item.val);
},
minLength: 0
}).focus(function () {
$(this).autocomplete("search");
});
});
</script>
Namespaces
You need to import the following namespaces.
C#
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
VB.Net
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
WebMethod
Inside the GetCustomers WebMethod, the records from the Customers table are fetched using SqlDataReader and are copied to the Generic List collection.
Finally, Generic List collection is returned to the Client Side
AJAX function.
C#
[WebMethod]
public static List<object> GetCustomers(string prefix)
{
List<object> customers = new List<object>();
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sql = "SELECT CustomerId, Name FROM Customers WHERE Name LIKE @SearchText + '%'";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@SearchText", prefix);
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new
{
val = sdr["CustomerId"],
label = sdr["Name"]
});
}
}
con.Close();
}
}
return customers;
}
VB.Net
<WebMethod>
Public Shared Function GetCustomers(ByVal prefix As String) As List(Of Object)
Dim customers As List(Of Object) = New List(Of Object)()
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sql As String = "SELECT CustomerId, Name FROM Customers WHERE Name LIKE @SearchText + '%'"
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@SearchText", prefix)
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(New With {
.val = sdr("CustomerId"),
.label = sdr("Name")
})
End While
End Using
con.Close()
End Using
End Using
Return customers
End Function
Displaying Name and CustomerId of Selected Customer
When Submit button is clicked, the Name and CustomerId of selected customer are fetched form the Request.Form collection.
Finally, the
Name and
CustomerId are displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnSubmit(object sender, EventArgs e)
{
string customerName = Request.Form[txtName.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(txtName.UniqueID)
Dim customerId As String = Request.Form(hfCustomerId.UniqueID)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Name: " & customerName & "\nID: " & customerId & "');", True)
End Sub
Screenshot
Downloads