[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:

[ServiceContract(Namespace="http://wcf.runningbarbus.com/2011/")]
public interface IRunningBarbusService
{
    [OperationContract]
    [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:

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

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:

http://localhost/Services/RunningBarbusService.svc/GetTeamData?TeamId=1&WeekNumber=2

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

function GetTeamData(teamId, weekNumber) {
    $.ajax(
    {
        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!