Make AJAX JSON call to ASP.Net WCF Service using jQuery and Javascript
 
Author:
Filed Under: ASP.Net  |  C#.Net  |  JavaScript  |  AJAX  |  VB.Net  |  JQuery  |  WCF
Published Date: Aug 17, 2011
Views: 2978
 

Abstract: Here Mudassar Ahmed Khan has explained how to modify the ASP.Net WCF (Windows Communication Foundation) service to make it accept AJAX JSON calls and to make AJAX JSON calls to ASP.Net WCF Service using JavaScript and jQuery

Comments:  2

 

In this article I will explain how to call ASP.Net WCF service using jQuery AJAX
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 jQuery and JavaScript
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.
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 jQuery AJAX 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)]
    string GetCustomers(string prefix);
}
 
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
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 string GetCustomers(string prefix)
      {
        List<object> customers = new List<object>();
        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", prefix);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(new
                        {
                            Id = sdr["CustomerId"],
                            Name = sdr["ContactName"]
                        });
                    }
                }
                conn.Close();
            }
            return (new JavaScriptSerializer().Serialize(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 prefix As String) As String
        Dim customers As New List(Of Object)()
        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", prefix)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        customers.Add(New With { _
                         Key .Id = sdr("CustomerId"), _
                         Key .Name = sdr("ContactName") _
                        })
                    End While
                End Using
                conn.Close()
            End Using
            Return (New JavaScriptSerializer().Serialize(customers))
        End Using
    End Function
End Class
 
Explanation: Above I am accepting a parameter prefix from the client side jQuery AJAX function. This parameter is used to search for the customers in the Customers table of the Northwind Database.
The returned results are added to a generic list of objects which is later serialized to a JSON string using JavaScriptSerializer.
 
Client Side AJAX JSON Call using jQuery
Below is the HTML Mark up of client web page that will access the ASP.Net AJAX WCF service that we created. It simply calls the ASP.Net AJAX WCF service along with the method name and the returned results are displayed.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type = "text/javascript">
        $("#search").live("click", function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '<%=ResolveUrl("~/Services/Service.svc/GetCustomers") %>',
                data: '{"prefix": "' + $("#prefix").val() + '"}',
                processData: false,
                dataType: "json",
                success: function (response) {
                    var customers = eval(response.d);
                    var html = "";
                    $.each(customers, function () {
                        html += "<span>Name: " + this.Name + " Id: " + this.Id + "</span><br />";
                    });
                    $("#results").html(html == "" ? "No results" : html);
                },
                error: function (a, b, c) {
                    alert(a.responseText);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input type = "text" id = "prefix" />
    <input id = "search" type = "button" value = "Search" />
    <div id = "results"></div>
    </form>
</body>
</html>
 
Explanation: On the click of the button search an AJAX JSON call is made to the ASP.Net AJAX WCF service. The value of the parameter prefix is picked from the textbox prefix.
The results returned from the ASP.Net AJAX WCF service are converted to JSON Array. Then a jQuery loop is executed over the array to make it and the results are displayed in a DIV as show in the following screenshot
 
Screenshot
Make AJAX JSON call to ASP.Net AJAX Enabled WCF Service using JavaScript and jQuery

Downloads
You can download the complete working source code in C# and VB.Net using the download link provided below.
 








Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit