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

November 14th, 2011 | Posted by Tom in .NET | JQuery | WCF | Read: 21,154

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!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

2 Responses

  • oxid says:

    this is the first code i found in the web (stackoverflow and codeproject both failed) that actually works.

    i was able to invoke the WCF service from url, and the result json object is shown in the browser.. but when i try to do the same via a jquery call, i get an error back.

  • hemantrhtk says:

    Asynchronous call to WebService / WCF using JQuery :
    You can use JQuery.Ajax to call web service :
    $.ajax({
    type: Type, //GET or POST or PUT or DELETE verb
    url: Uri, // Location of the service
    // data: Data, //Data sent to server
    dataType: DataType, //Expected data format from server

    cache: false, // no-cache
    success: function (msg) {//On Successfull service call
    ServiceSucceeded(msg);
    },
    error: ServiceFailed// When Service call fails
    });
    Sample source code :
    http://sharepoint.asia/asynchronous-call-to-web-services-using-jquery/



Add Comment Register



Leave a Reply