Saturday 22 March 2014

Calling WCF From Jquery/Javascrip

Three things are to be taken care for a WCF to be invoked from javascript.
  1. The Service has to be decorated with WebInvoke/WebGet to be accessed from javascript.
  2. <enableWebScript/> has to be added to the configuration for enabling script calls to WCF.
  3. webHttpBinding is to be used for the WCF to behave as a REST service.
The service have a single method RepeatString:

[OperationContract]
[WebGet(UriTemplate = "/repeatstring",
ResponseFormat= WebMessageFormat.Json)]
string RepeatString(string s, int times);
[OperationContract]
public string RepeatString(string s, int times)
{
   string result = "";

   for (int i = 0; i < times; ++i)
   {
       result += s;
   }


   return result;
}
configuration

<system.serviceModel>
 <behaviors>
  <serviceBehaviors>
    <behavior name="DatingServiceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="DatingServiceBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="DatingServiceBehavior"
           name="DatingService.Service.DatingService">
    <endpoint address="" binding="webHttpBinding"
       contract="DatingService.Service.IDatingService"
       behaviorConfiguration="DatingServiceBehavior"/>
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
 </services>
</system.serviceModel>
jquery
function callAjaxService1() {    
    $.post("~/AjaxService1.svc/RepeatString", {s : 'Test', times : 12},
        function(data) {
            alert('data from service');
        }, 'json');

}

No comments:

Post a Comment