In this article I will explain how to consume WCF Rest using jQuery AJAX and make JSON calls in ASP.Net.
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>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="ServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceAspNetAjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
VB.Net
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="ServiceAspNetAjaxBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="webHttpBinding" contract="Service" behaviorConfiguration="ServiceAspNetAjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint contract="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
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.
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.
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
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.
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.
<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>
Screenshot
Downloads