转[http://blogs.msdn.com/b/sharepointdev/archive/2011/02/22/calling-a-wcf-service-using-jquery-in-sharepoint.aspx]
This blog post explains how a WCF service can be called using jQuery in a SharePoint application. I won’t cover all of the implementation details. This post will highlight the relevant parts of configuring a WCF service to be accessible using jQuery in SharePoint.
[Update – 2/23/2011 – The original post contained some poor deployment practices and erroneous code. We apologize for the errors and want to give a big thank you to Wictor Wilen for pointing them out. The best practices for deployment and development using Visual Studio 2010 are available on his blog post . We are working to create a technical article that will show the best practices and Visual Studio 2010 tools.]
Let us start with the creation of Data Access Layer. This consists of the ProductsManager class and the associated methods.
public List<Products> GetProducts() { List<Products> productsList = new List<Products>(); Database DatabaseInstance = DatabaseFactory.CreateDatabase(ConnectionStringkey); DbCommand DatabaseCommand; using (DatabaseCommand = DatabaseInstance.GetStoredProcCommand(SP_GetProducts)) { using (IDataReader reader = DatabaseInstance.ExecuteReader(DatabaseCommand)) { while (reader.Read()) { Products products = new Products(); products.ProductName = reader["ProductName"].ToString(); products.ProductDesc = reader["ProductDesc"].ToString(); products.Price = reader["Price"].ToString(); products.Quantity = reader["Quantity"].ToString(); productsList.Add(products); } } return productsList; } }
Now, we will create the WCF Service. This will serve the data to our page. Since this will be deployed to SharePoint, make sure the target framework is .NET Framework 3.5.
Now, we will configure the Web.config entries as well as the attributes for the services.
<%@ ServiceHost Language="C#" Debug="true" Service="SampleWCFService.ProductService"
CodeBehind="ProductService.svc.cs"
Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory,
Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
using Microsoft.SharePoint.Client.Services; using System.ServiceModel.Activation;
[BasicHttpBindingServiceMetadataExchangeEndpoint] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
/// <summary> /// Gets the list of Products /// </summary> /// <returns>Returns the List of Products</returns> public List<Products> GetProducts() { ProductsManager productsManager = new ProductsManager(); return productsManager.GetProducts(); }
[OperationContract] [WebGet(UriTemplate = "/GetProducts", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] List<Products> GetProducts();
Deploying WCF Service in SharePoint environment
[Update – 2/23/2011 - Our original post contained manual instructions for copying files to the front-end, and this is not a best practice. Deployment should be handled using the tools provided in Visual Studio 2010 or through the use of a redistributable solution package. Wictor Wilen covers this topic on his blog post. Please refer to his post for help with deploying the files using Visual Studio 2010.]
In order to check whether the Service is up, navigate to http://siteurl/_layouts/ProductService.svc from your browser. You will see a message “No End Point” on the screen. Now, let’s try to access the method GetProducts by navigating to http://siteurl/_layouts/ProductService.svc/GetProducts from the browser again. It pops up the resultant file.
Accessing WCF Service using jQuery from a SharePoint site
Now, it’s time to access this WCF service using jQuery. Create a JS file with name CallWCFService.Js and use the following snippets to call the service.
function Product(ProductName, ProductDesc, Price, Quantity) { this.ProductName = ProductName; this.ProductDesc = ProductDesc; this.Price = Price; this.Quantity = Quantity; }
function CallWCFService(WCFServiceURL) { $.ajax({ type: "GET", url: WCFServiceURL, contentType: "application/json; charset=utf-8", dataType: 'json', processdata: true, success: function (msg) { WCFServiceSucceeded(msg); }, error: WCFServiceFailed }); }
//On Successful WCF Service call function WCFServiceSucceeded(result) { var productsArray = new Array(); //Gets the Products $.each(result, function (i, Product) { productsArray[i]=Product; }); //Print all the product details $.each(productsArray,function(i,Product) { alert(Product.ProductName + ' ' + Product.ProductDesc + ' ' + Product.Price + ' ' + Product.Quantity) }); }
<script src="/Style Library/callwcfservice.js" type="text/javascript"></script>