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

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;

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Books
{
    [OperationContract]
    [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);
        myConn.Open();

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

        while (reader.Read())
        {
            lstBooks.Add(reader["BookName"].ToString());
        }

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

<ServiceContract()>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Books
    <OperationContract()>
            <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)
        myConn.Open()

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

        While reader.Read()
            lstBooks.Add(reader("BookName").ToString())
        End While

        myConn.Close() : Return lstBooks
    End Function
End Class
Configure the “web.config” file
<system.serviceModel>
    <!--DEFINE YOUR SERVICES WITH ENDPOINTS-->
    <services>
      <service name="Books" behaviorConfiguration="MyServiceBehavior"> 
            <!--REFERENCES THE SERVICE BEHAVIORS-->
        <endpoint 
            address="" 
            binding="webHttpBinding" 
            behaviorConfiguration="webEndPointBehavior" 
            name="webEndPoint" 
            contract="Books" />
      </service>
    </services>
    
    <behaviors>
      <!--SERVICE BEHAVIORS-->
      <serviceBehaviors>
        <behavior name="MyServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>

      <!--ENDPOINT BEHAVIORS-->
      <endpointBehaviors> 
        <behavior name="webEndPointBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
The Markup and Script
<!DOCTYPE html />
<html>
<head>
    <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
</head>
<body>
    <div style="font:15px Arial;">
        <b>Books</b>:  <input id="tbBooks" type="text" runat="server" />
    </div>
</body>

// THE SCRIPT.
<script>
    $(document).ready(function () {
        BindControls();
    });

    function BindControls() {
        $("#tbBooks").autocomplete({
            source: function (request, response) {

                var val = request.term;

                $.ajax({
                    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) {
                        alert(textStatus);
                    }
                });
            },
            minLength: 1    // MINIMUM 1 CHARACTER TO START WITH.
        });
    }
</script>
</html>

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 - Difference between Asp.Net WCF Services and ASMX Web Services



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: