In this article I will explain how to use ASP.Net AJAX Control Toolkit AutoCompleteExtender using ASP.Net WCF (Windows Control Foundation) web service.
 
Database
For database I am using the Microsoft’s Northwind Database. You can download the same using the link below
 

Connection String
 
Below is the connection string to the database which I have placed in the web.config.
<connectionStrings>
<add name="constr" connectionString="Data Source = .\SQL2005;
Initial Catalog = Northwind; Integrated Security = true"/>
</connectionStrings>
 
Adding and configuring the WCF Service
We need to make some configuration changes to the ASP.Net WCF service in order to make it available to ASP.Net AJAX Control Toolkit AutoCompleteExtender
1. Adding AspNetCompatibilityRequirements Attribute
Add the AspNetCompatibilityRequirements attribute for the Service class to make the WCF service behave like an ASP.Net ASMX Web Service and will able to process requests via HTTP in the following way
 
C#
 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
}
 
VB.Net
 
<ServiceContract()> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service
 
End Class
 
 
2. Adding ASP.Net AJAX endpoint behaviour
Add the following ASP.Net AJAX endpoint behaviour in the Web.Config file to enable AJAX calls to the service from the ASP.Net AJAX Control Toolkit AutoCompleteExtender
C#
<system.serviceModel>
      <behaviors>
            <serviceBehaviors>
                  <behaviorname="ServiceBehavior">
                        <serviceMetadatahttpGetEnabled="true"/>
                        <serviceDebugincludeExceptionDetailInFaults="true"/>
                  </behavior>
            </serviceBehaviors>
        <endpointBehaviors>
            <behaviorname="ServiceAspNetAjaxBehavior">
                <enableWebScript />
            </behavior>
        </endpointBehaviors>
      </behaviors>
    <serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/>
    <services>
            <servicebehaviorConfiguration="ServiceBehavior"name="Service">
                  <endpointaddress=""binding="webHttpBinding"contract="IService"behaviorConfiguration="ServiceAspNetAjaxBehavior">
                        <identity>
                              <dnsvalue="localhost"/>
                        </identity>
                  </endpoint>
                  <endpointaddress="mex"binding="mexHttpBinding"contract="IMetadataExchange"/>
            </service>
      </services>
</system.serviceModel>
 
VB.Net
<system.serviceModel>
      <behaviors>
        <serviceBehaviors>
                  <behaviorname="ServiceBehavior">
                        <serviceMetadatahttpGetEnabled="true"/>
                        <serviceDebugincludeExceptionDetailInFaults="true"/>
                  </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                  <behaviorname="ServiceAspNetAjaxBehavior">
                        <enableWebScript/>
                  </behavior>
            </endpointBehaviors>
      </behaviors>
      <serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/>
      <services>
            <servicename="Service"behaviorConfiguration="ServiceBehavior">
            <endpointaddress=""binding="webHttpBinding"contract="Service"behaviorConfiguration="ServiceAspNetAjaxBehavior">
                <identity>
                    <dnsvalue="localhost"/>
                </identity>
            </endpoint>
            <endpointcontract="IMetadataExchange"binding="mexHttpBinding"address="mex" />
        </service>
      </services>
</system.serviceModel>
 
3. Adding the WebInvoke attribute
 
Add the WebInvoke attribute for the method to specify the Method and the ResponseFormat in the following way
 
C#
 
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "POST",
    ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
string GetCustomers(string prefix);
 
 
VB.Net
 
<System.ServiceModel.Web.WebInvoke(Method:="POST", _
        ResponseFormat:=System.ServiceModel.Web.WebMessageFormat.Json)> _
Public Function GetCustomers(ByVal prefix As String) As String
 
That’s it all we need to do to configure the web service
 
Building the WCF Service Method
Now we will build the WCF Service method that the ASP.Net AJAX AutoCompleteExtender will call to get the data from the server. Basically it is a simple function that searches the Customers table of the Northwind database and returns the records of the matched customers.
C#
IService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
 
[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
    List<string> GetCustomers(string prefixText, int count);
}
 
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;
using System.ServiceModel.Activation;
 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    public List<string> GetCustomers(string prefixText, int count)
      {
        List<string> customers = new List<string>();
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select ContactName, CustomerId from Customers where " +
                "ContactName like @prefix + '%'";
                cmd.Parameters.AddWithValue("@prefix", prefixText);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        string item = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(sdr["ContactName"].ToString(), sdr["CustomerId"].ToString());
                        customers.Add(item);
                    }
                }
                conn.Close();
            }
            return customers;
        }
    }
}
 
VB.Net
Service.vb
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.Text
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Script.Serialization
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web
Imports System.Web.Script.Services
 
<ServiceContract()> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service
    <OperationContract()> _
    <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _
    Public Function GetCustomers(ByVal prefixText As String, ByVal count As Integer) As List(Of 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 @prefix + '%'"
                cmd.Parameters.AddWithValue("@prefix", prefixText)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        Dim item As String = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(sdr("ContactName").ToString, sdr("CustomerId").ToString)
                        customers.Add(item)
                    End While
                End Using
                conn.Close()
            End Using
            Return customers
        End Using
    End Function
End Class
 
Explanation: Above I am accepting a parameter prefixText and count which are passed from client side by the ASP.Net AJAX Control Toolkit AutoCompleteExtender. The prefixText parameter is used to search for the customers in the Customers table of the Northwind Database.
The returned results are converted to an ASP.Net AJAX Control Toolkit AutoCompleteItem and then added to a generic list of string.
 
Client Side configuration
Registering the AjaxControlToolkit Library
The following line needs to be added to the page in order to register the AjaxControlToolkit Library
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
 
HTML Mark up
Below is the HTML Mark up of client web page with the ASP.Net ScriptManager and the ASP.Net AJAX AutoCompleteExtender control that will access the ASP.Net AJAX WCF service that we created.
The ServicePath property is set to the URL of the ASP.Net WCF Service and the ServiceMethod property is set to the WCF Service method GetCustomers.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
  
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"
        EnablePageMethods = "true">
        </asp:ScriptManager>
 
        <asp:TextBox ID="txtCustomers" runat="server"></asp:TextBox>
        <cc1:AutoCompleteExtender ServiceMethod="GetCustomers"
        MinimumPrefixLength="2" ServicePath = "~/Services/Service.svc"
        CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
        TargetControlID="txtCustomers"
        ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
        </cc1:AutoCompleteExtender>
    </form>
</body>
</html>
 
Screenshot
Implement ASP.Net AJAX Control Toolkit AutocompleteExtender using WCF Web Service
Downloads
You can download the complete working source code in C# and VB.Net using the download link provided below.