I described how to develop a custom WCF service. Today I’ll cover how you can invoke the SharePoint WCF Service from jQuery. In my last post I described to develop a SOAP web service but for using WCF service from jQuery I’m going to use REST web service. For the list of service types and factories supported in SharePoint you can visit the link in MSDN. You can download source code from the link given at the end of the post.
Prepare the service to call from jQuery
- For using json I’ve used REST service factory ‘Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory’ as shown below. You can use SOAP factory but you then need to parse data in different way.
<%@ ServiceHost Language="C#" Debug="true" Service="AccessSPServiceFromJQuery.MyService, $SharePoint.Project.AssemblyFullName$" CodeBehind="MyService.svc.cs" Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory,
Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral,PublicKeyToken=71e9bce111e9429c" %> - Next you need to specify the return type to json in the service interface as shown below. I’ve specified both request and response type to json in WebInvoke attribute:
[ServiceContract] public interface IMyService { [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)] List<Product> SearchProduct(string productName); [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)] bool Save(Product product); }
Call Service with jQuery
function getProductFromService(searchText) { try { $.ajax({ type: "GET", url: '/_vti_bin/AccessSPServiceFromJQuery/MyService.svc/SearchProduct', contentType: "application/json; charset=utf-8", data: { "productName": searchText }, dataType: 'json', success: function (msg) { WCFServiceGetSucceeded(msg); }, error: WCFServiceGetFailed }); } catch (e) { alert('error invoking service.get()' + e); } } function WCFServiceGetSucceeded(result) { alert('success'); } function WCFServiceGetFailed(error) { alert('Service Failed.'); }



