AutoComplete using jQuery Ajax and Asp.Net WCF Service – C# and Vb.Net

← PrevNext →

In one of my previous article, I have written about a jQuery Plug-in to AutoComplete text by calling a Web Service method. Let’s take that example to the next level. Here, in this article we’ll discuss with an example, on AutoComplete text using jQuery Ajax and by invoking a WCF Service method.

AutoComplete text using jQuery and WCF Service

The jQuery Plug-in, which I am going to use in my example here, is very flexible. It not only allows us to hook it with an array of data at the client side, but also with a database table situated at a remote server.

Create a WCF Service

If you have previously worked with ASMX services and have recently upgraded to WCF, then you must be aware of the advantages WCF services enjoy over ASMX services. I have written an article that has a detail description about the Difference between WCF Services and ASMX Services.

The WCF service that I am going to create is very simple. When a user type a letter in the textbox on the web page, the jQuery Ajax with JSON, invokes the WCF service. The service method returns a list of string values, extracted from a database table (dbo.Books).

Add a WCF service to your project and name it Books.svc. Our service method is inside the class Books.cs (Books.vb in Vb.Net). However, you are free to use the Interface in your project and implement the methods directly from the interface. I want to keep the example simple and therefore I'll ignore the implementation part.

Moreover, if you are still reluctant on using an Interface and follow standard procedures, then I recommend you first go through the article on How to create a WCF service and call the service using jQuery. The code is written in both C# and in Vb.Net

C# Class (Books.cs)
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.ServiceModel;                  // FOR CONTRACTS.
using System.ServiceModel.Activation;       // FOR AspNet COMPATIBILITY MODE.
using System.ServiceModel.Web;              // FOR [WebInvoke].
using System.Data.SqlClient;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Books
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    public List<string> ShowBooks(string sLookUP)
        List<string> lstBooks = new List<string>();

        string sConnString = "Data Source=DNA;Persist Security Info=False;" + 
            "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;";

        SqlConnection myConn = new SqlConnection(sConnString);
        SqlCommand objComm = new SqlCommand("SELECT BookName FROM dbo.Books " + 
            "WHERE BookName LIKE '%'+@LookUP+'%' ORDER BY BookName", myConn);

        objComm.Parameters.AddWithValue("@LookUP", sLookUP);
        SqlDataReader reader = objComm.ExecuteReader();

        while (reader.Read())

        return lstBooks;
Vb.Net Class (Books.vb)
Imports System.ServiceModel.Activation
Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.Data.SqlClient

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Books
            <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, 
                BodyStyle:=WebMessageBodyStyle.WrappedRequest)> _
    Public Function ShowBooks(ByVal sLookUP As String) As List(Of String)
        Dim lstBooks As New List(Of String)()

        Dim sConnString As String = "Data Source=DNA;Persist Security Info=False;" & _
            "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;"

        Dim myConn As New SqlConnection(sConnString)
        Dim objComm As New SqlCommand("SELECT BookName FROM dbo.Books " & _
            "WHERE BookName LIKE '%'+@LookUP+'%' ORDER BY BookName", myConn)

        objComm.Parameters.AddWithValue("@LookUP", sLookUP)
        Dim reader As SqlDataReader = objComm.ExecuteReader()

        While reader.Read()
        End While

        myConn.Close() : Return lstBooks
    End Function
End Class
Configure the “web.config” file
      <service name="Books" behaviorConfiguration="MyServiceBehavior"> 
            contract="Books" />
        <behavior name="MyServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>

        <behavior name="webEndPointBehavior">
          <webHttp />
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
The Markup and Script
<!DOCTYPE html />
    <link href="" rel="stylesheet" type="text/css"/>
    <script src=""></script>
    <script src=""></script>
    <div style="font:15px Arial;">
        <b>Books</b>:  <input id="tbBooks" type="text" runat="server" />

    $(document).ready(function () {

    function BindControls() {
            source: function (request, response) {

                var val = request.term;

                    url: "Books.svc/ShowBooks",
                    data: JSON.stringify({ sLookUP: val }),
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { value: item }
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
            minLength: 1    // MINIMUM 1 CHARACTER TO START WITH.

url: It has the path for Books.svc file and the WCF method which is invoked by jQuery Ajax. When a user enters at least one character (we have set minLength to 1) in the textbox, it triggers the jQuery AutoComplete method to invoke the WCF method at the server. The path can vary depending on the location of the calling files.

url: "Books.svc/ShowBooks"

We are hoping you will find this article interesting and helpful. Share it with your friends. However, do write to us if you have any suggestions or tips related to this article.

← Previous