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.

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;

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

[DataContract()]
public class BookDetails
{
    string sBookName;
    string sCategory;

    double dPrice;
    [DataMember()]
    public string Name
    {
        get { return sBookName; }
        set { sBookName = value; }
    }

    [DataMember()]
    public string Catagory
    {
        get { return sCategory; }
        set { sCategory = value; }
    }

    [DataMember()]
    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 = 
                            AspNetCompatibilityRequirementsMode.Allowed)]
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

<ServiceContract()>
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
        Get
            Return sBookName
        End Get
        Set(value As String)
            sBookName = value
        End Set
    End Property

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

    <DataMember()> _
    Public Property Price() As Double
        Get
            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

<AspNetCompatibilityRequirements(RequirementsMode:=
                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.

<system.serviceModel>
    <!--DEFINE YOUR SERVICES WITH ENDPOINTS-->
    <services>
        <service name="Books" 
            <!--REFERENCES THE SERVICE BEHAVIORS-->
            behaviorConfiguration="MyServiceBehavior">

             <endpoint 
                address="" 
                binding="webHttpBinding" 
                <!--REFERENCES THE ENDPOINT BEHAVIORS-->
                behaviorConfiguration="webEndPointBehavior"
                name="webEndPoint" 
                contract="IBooks"/>
        </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 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>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
</head>
<body>
    <form runat="server">
    <div class="page">
        <div class="main">
            <div>
                <h2><strong>Calling WCF Service using Ajax and JSON</strong></h2><br />
                <div>
                    <b>Enter Book ID</b>:  <input id="txtID" type="text" runat="server" />
                </div>

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

                <div style="margin:10px auto;">
                    <input type="button" value="Submit" id="btSubmit" runat="server" />
                </div>
            </div>
        </div>
    </div>
    </form>
</body>
    <script>
        $('#btSubmit').click(function () {
            $.ajax({
                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) {
                    alert(textStatus);
                }
            });
        });
    </script>
 </html>

JSON.stringify() Method

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

Syntax

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

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

Conclusion

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.

🙂

← PreviousNext →