In this article I will explain how to make the jQuery AutoComplete TextBox work inside ASP.Net Master Page using C# and VB.Net.
When jQuery AutoComplete is placed inside Master Page, it does not work as Master Page does not have any visual presence when the website runs. Master Pages are basically used for web page design purposes.
Thus in order to make jQuery AutoComplete work in Master Page, a Web Service is used.
This article uses Microsoft’s Northwind Database. You can download it using the download link provided below.
Building the Web Service
1. First step is to add a Web Service.
Implement jQuery AutoComplete inside Master Page in ASP.Net
2. Once the Web Service is added. You will need to add the following namespaces.
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Services;
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Script.Services
3. Third step is to add the WebMethod to get data from database for jQuery AutoComplete.
Below is the code for the web service which will handle the jQuery Autocomplete calls and will return the matching records from the Customers table of the Northwind database.
The select query gets the Name and the ID of the customer that matches the prefix text.
The fetched records are processed and a Key Value Pair is created by appending the Id to the Name field in the following format {0}-{1} where is the Name {0} and {1} is the ID of the Customer.
By default the Web Service will not accept requests from client side sent using jQuery AJAX. In order to allow a Web Service handle jQuery AJAX calls, the ScriptService attribute needs to be specified to the Web Service class.
/// Summary description for Service
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
public class Service : System.Web.Services.WebService {
    public Service () {
        //Uncomment the following line if using designed components
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string[] GetCustomers(string prefix)
        List<string> customers = new List<string>();
        using (SqlConnection conn = new SqlConnection())
            conn.ConnectionString = ConfigurationManager
            using (SqlCommand cmd = new SqlCommand())
                cmd.CommandText = "select ContactName, CustomerId from Customers where " +
                "ContactName like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefix);
                cmd.Connection = conn;
                using (SqlDataReader sdr = cmd.ExecuteReader())
                    while (sdr.Read())
                        customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
            return customers.ToArray();
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<ScriptService()> _
Public Class Service
    Inherits System.Web.Services.WebService
    <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Function GetCustomers(ByVal prefix As String) As String()
        Dim customers As New List(Of String)()
        Using conn As New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As New SqlCommand()
                cmd.CommandText = "select ContactName, CustomerId from Customers where " & "ContactName like @SearchText + '%'"
                cmd.Parameters.AddWithValue("@SearchText", prefix)
                cmd.Connection = conn
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        customers.Add(String.Format("{0}-{1}", sdr("ContactName"), sdr("CustomerId")))
                    End While
                End Using
            End Using
            Return customers.ToArray()
        End Using
    End Function
End Class
Client Side Implementation
The following HTML Markup of Master Page consists of an ASP.Net TextBox, a HiddenField and a Button.
The jQuery AutoComplete plugin has been applied to the TextBox. A jQuery AJAX call is made to the GetCustomers WebMethod of the Web Service and the list of customers returned from the WebMethod acts as source of data to the jQuery AutoComplete.
You will notice that I have used [id$=txtSearch] as jQuery Selector for the ASP.Net TextBox, these are known as jQuery Wildcard selectors and you can learn more about it in my article Find ASP.Net controls when using Master Page and Content Page using jQuery.
The data received from the server is processed in the jQuery AJAX call success event handler. A loop is executed for each received item in the list of items and then an object with text part in the label property and value part in the val property is returned.
A Select event handler has been defined for the jQuery AutoComplete and when an item is selected from the AutoComplete List, the value of the item is stored in the HiddenField.
<html xmlns="">
<head id="Head1" runat="server">
    <asp:ContentPlaceHolder ID="head" runat="server">
    <form id="form1" runat="server">
       <script src="" type="text/javascript"></script>
    <script src=""
    <link href=""
        rel="Stylesheet" type="text/css" />
    <script type="text/javascript">
        $(function () {
                source: function (request, response) {
                        url: '<%=ResolveUrl("~/Service.asmx/GetCustomers") %>',
                        data: "{ 'prefix': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.split('-')[0],
                                    val: item.split('-')[1]
                        error: function (response) {
                        failure: function (response) {
                select: function (e, i) {
                minLength: 1
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <asp:HiddenField ID="hfCustomerId" runat="server" />
    <br />
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" />
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
Fetching the Selected Item Key and Value server side
The Key (Customer Name) and Value (Customer ID) can be fetched on server side inside the click event handler of the Button from the Request.Form collection as shown below.
protected void Submit(object sender, EventArgs e)
    string customerName = Request.Form[txtSearch.UniqueID];
    string customerId = Request.Form[hfCustomerId.UniqueID];
Protected Sub Submit(ByVal sender As Object, ByVal e As System.EventArgs)
   Dim customerName As String = Request.Form(txtSearch.UniqueID)
  Dim customerId As String = Request.Form(hfCustomerId.UniqueID)
End Sub
Working of the jQuery Autocomplete using Web Services
Implement jQuery AutoComplete inside Master Page in ASP.Net
Fetching the Key and Value of the selected Autocomplete Item
Implement jQuery AutoComplete inside Master Page in ASP.Net