[JQuery] How to call a WCF service from JQuery ?

November 14th, 2011 | Posted by Tom in .NET | JQuery | WCF - (2 Comments)

Blogging about JQuey/Javascript is a bit new for me but it’s not too late to change :-)

Today, I’ll try to show how you can have a JQuery script that call a simple WCF service.

The first part to achieve this result is to expose your WCF service so it can be accessed using REST and JSON. So apply the WebInvoke attribute to your service:

public interface IRunningBarbusService
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "GET", BodyStyle=WebMessageBodyStyle.WrappedRequest)]
    List<RunDto> GetTeamData(int teamId, int weekNumber);

Now, modify your web.config’s file to expose the service through enableWebScript, an endpoint behavior that makes it possible to consume the service from ASP.NET AJAX pages:

      <service name="RunningBarbus.Services.RunningBarbusService" behaviorConfiguration="DefaultBehavior">
        <endpoint address="" binding="webHttpBinding" contract="RunningBarbus.Services.IRunningBarbusService" name="RunningBarbus.Services.RunningBarbusService" behaviorConfiguration="AjaxBehavior">
            <dns value="locahost" />
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        <behavior name="AjaxBehavior">
          <enableWebScript />
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />

Your WCF service is now available using an URL list: http://localhost/YourService.svc/YourMethod?Param=Value, so, in my case, I was able to see the JSON corresponding to the results by browsing the URL:


To finish, you just need access this URL, passing the correct parameters, using JQuery:

function GetTeamData(teamId, weekNumber) {
        async: true,
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "../../Services/RunningBarbusService.svc/GetTeamData",
        dataType: "json",
        data: '{"teamId":"' + teamId + '", "weekNumber":"' + weekNumber + '"}',
        success: function (content) {
            DisplayRun(map, content);

And that’s all ! Pretty simple but very useful, you can now access any WCF services from JQuery !


Happy coding!