Create a WCF Service and call the Service using jQuery Ajax and JSON – C# and Vb.Net

← PrevNext →

We can call WCF services using codes written in jQuery Ajax and JSON. Therefore, in this article we will explain how we can create a WCF service and later call the service using jQuery Ajax and JSON. We have designed and written the codes using C# and Vb.Net.

If you are an absolute beginner to WCF and its concepts, then we honestly suggest you first read and understand the basics of WCF service, and learn the fundamentals of various WCF contracts, such as Message Contract, WCF Data Contract.

WCF is virtually incomplete without its Endpoints. You must learn the ABC’s of endpoint , so you can properly connect with WCF concepts.

WCF uses the web.config file extensively to define its services, behaviors and endpoints. We will also explain the various sections of configuration later in this article.

Our WCF Service

First, we will create a service, which we will call from a client code using jQuery. As usual, our service is very simple. A Book library, which stores details about various books. When a client enters the ID, the service returns few important details about book.

Open visual studio and create a New Web Site… using your chosen language (C# or Vb.Net). In the Solution Explorer window, right click the project and select Add New Item…. Choose WCF Service and name the service as Books.svc.

In the IBooks interface, add the below code. The Service Contract IBooks has an OperationContract and a DataContract, with three DataMembers Name, Category and Price.

Before you scroll down and look deep inside the code, we need to explain two attributes which we have added in our interface and in the class.

01) <WebInvoke(Method = … : The WebInvoke attribute exposes services using POST, PUT etc. The default is POST. Read this MSDN article to learn more on WebInvoke.
02) AspNet Compatibility Mode: We have used this attribute in the Books class that implements the interface. Looks pretty much the same as an ASMX service.

It indicates whether a service supports Asp.Net Compatibility mode. We have set the mode as Allowed, and this is the default mode.

Related: Asp.Net Web API Example – AutoComplete Textbox using jQuery and Web API

C# Interface (IBooks.cs)
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Web;

public interface IBooks
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
    BookDetails ShowBookDetails(string sBookID);

public class BookDetails
    string sBookName;
    string sCategory;

    double dPrice;
    public string Name
        get { return sBookName; }
        set { sBookName = value; }

    public string Catagory
        get { return sCategory; }
        set { sCategory = value; }

    public double Price
        get { return dPrice; }
        set { dPrice = value; }
C# Class (Book.cs)
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.ServiceModel.Activation;

[AspNetCompatibilityRequirements(RequirementsMode = 
public class Books : IBooks
    public BookDetails ShowBookDetails(string sBookID)
        BookDetails objBookDetails = new BookDetails();

        if (sBookID == "001")
            objBookDetails.Name = "Asp.Net 4 Blue Book";
            objBookDetails.Catagory = "Programming";
            objBookDetails.Price = 56;

        return objBookDetails;
Vb.Net Interface (IBooks.vb)
Imports System.ServiceModel
Imports System.Runtime.Serialization
Imports System.ServiceModel.Web

Public Interface IBooks
    <OperationContract()> _
        <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _
    Function ShowBookDetails(ByVal sBookID As String) As BookDetails
End Interface

<DataContract()> _
Public Class BookDetails
    Dim sBookName As String
    Dim sCategory As String
    Dim dPrice As Double

    <DataMember()> _
    Public Property Name() As String
            Return sBookName
        End Get
        Set(value As String)
            sBookName = value
        End Set
    End Property

    <DataMember()> _
    Public Property Catagory() As String
            Return sCategory
        End Get
        Set(value As String)
            sCategory = value
        End Set
    End Property

    <DataMember()> _
    Public Property Price() As Double
            Return dPrice
        End Get
        Set(value As Double)
            dPrice = value
        End Set
    End Property
End Class
Vb.Net Class (Books.vb)
Imports System.ServiceModel.Activation

                AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Books
    Implements IBooks

    Public Function ShowBookDetails(sBookID As String) As BookDetails Implements IBooks.ShowBookDetails

        Dim objBookDetails As New BookDetails

        If sBookID = "001" Then
            objBookDetails.Name = "Asp.Net 4 Blue Book"
            objBookDetails.Catagory = "Programming"
            objBookDetails.Price = 56
        End If

        Return objBookDetails
    End Function
End Class
Configuring the “web.config” file

We now need to configure our WCF service.

        <service name="Books" 

        <!--SERVICE BEHAVIORS-->
            <behavior name="MyServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="true"/>

            <behavior name="webEndPointBehavior">
                <webHttp />
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

The web.config will have three important sections.

01) Services with endpoints
02) The Service Behaviors
03) The Endpoint Behaviors

The Client Interface Using jQuery

The Markup and Script

<!DOCTYPE html>
    <script src=""></script>
    <script src=""></script>
    <form runat="server">
    <div class="page">
        <div class="main">
                <h2><strong>Calling WCF Service using Ajax and JSON</strong></h2><br />
                    <b>Enter Book ID</b>:  <input id="txtID" type="text" runat="server" />

                <div id="BooksDetails" runat="server" style="margin:10px 0;"> </div>

                <div style="margin:10px auto;">
                    <input type="button" value="Submit" id="btSubmit" runat="server" />
        $('#btSubmit').click(function () {
                url: "Books.svc/ShowBookDetails",
                data: JSON.stringify($('#txtID').val()),
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $('#BooksDetails').html('Name: ' + data.Name + '<br /> Catagory: ' + 
                        data.Catagory + '<br /> Price: $' + data.Price);
                error: function (XMLHttpRequest, textStatus, errorThrown) {

JSON.stringify() Method

The JSON.stringify() converts a value into a JSON string.


JSON.stringify(value [, replacer] [, space])

You can find more information about the JSON.stringify method in this MSDN link.


Creating a WCF service may not look very simple, but with a little practice, you can master the concept and create useful services. If you have previously worked with ASMX services, you might find some similarities in it.

Thanks for reading .

← PreviousNext →