In this article I will explain how to implement and populate jQuery AutoComplete TextBox using Generic Handler in ASP.Net using C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
HTML Markup
The following HTML Markup consists of an ASP.Net TextBox and a Button. The jQuery AutoComplete plugin has been applied to the TextBox. The ASP.Net Generic Handler is set as source of data to the jQuery AutoComplete plugin.
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("[id*=txtSearch]").autocomplete({ source: '<%=ResolveUrl("~/Search.ashx" ) %>' });
});
</script>
Enter search term:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
ASP.Net Generic Handler
The following Generic Handler accepts a QueryString parameter terms and its value is used to find matching records from the Customers Table of the Northwind database.
The matching records are returned as an Array of string after being serialized using JavaScriptSerializer.
C#
<%@ WebHandler Language="C#" Class="Search" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class Search : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["term"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ContactName from Customers where ContactName like @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefixText);
cmd.Connection = conn;
List<string> customers = new List<string>();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["ContactName"].ToString());
}
}
conn.Close();
context.Response.Write(new JavaScriptSerializer().Serialize(customers));
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
VB.Net
<%@ WebHandler Language="VB" Class="Search" %>
Imports System.Web
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Text
Imports System.Collections.Generic
Imports System.Web.Script.Serialization
Public Class Search : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim prefixText As String = context.Request.QueryString("term")
Using conn As New SqlConnection()
conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using cmd As New SqlCommand()
cmd.CommandText = "select ContactName from Customers where ContactName like @SearchText + '%'"
cmd.Parameters.AddWithValue("@SearchText", prefixText)
cmd.Connection = conn
Dim customers As New List(Of String)()
conn.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(sdr("ContactName").ToString())
End While
End Using
conn.Close()
context.Response.Write(New JavaScriptSerializer().Serialize(customers))
End Using
End Using
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Fetching the selected item on Server Side
The selected item can be fetched on server side inside the click event handler of the Button from the Request.Form collection as shown below.
C#
protected void Submit(object sender, EventArgs e)
{
string customerName = Request.Form[txtSearch.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + customerName + "');", true);
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim customerName As String = Request.Form(txtSearch.UniqueID)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Name: " & customerName & "');", True)
End Sub
Screenshot
Demo
Downloads