Mar 22, 2010

Consume SharePoint 2010 RESTful service from Ajax JavaScript

I ever post on how to Consume REST in SilverLight to bind SharePoint 2010 List Data. In this post, I will show how to consume SharePoint RESTful service in AJAX Javascript for databinding in a sharepoint application page (no authenticaion needed in this scenario).

First create an application page:

this should be easy to do by using Visual Studio 2010 sharepoint template, or you can simple manually creat one (see here).

Add AJAX library support into the application page:

This should be done simply by linking AJAX library from CDN. But as AJAX libray currently still in beta, you have to download MicrosoftAjax.js (this is needed only for dataview control used in the code) from here , add this file into your project file and then use ScriptManagerProxy to load it to the page (I think this should be a bug in beta). You can't use ScriptManger since sharepoint master page already has one.

The script should look like:


Invoke Ajax Call by using WebRequest, a traditional way

by default, RESTful service response with ATOM feed (XML formated). In order for AJAX to work, the request header should be specified as accepting application/json. This is important otherwise deserialization will fail.



In Callback, bind data with control:


with HTML makeup looks like this:


A even more elegant way, but not working yet... and it works!

In PDC 2009, a very elegant way was demoed by Stephen Walther to achieve this data binding with WCF service, but I can't make it work with listdata.svc. I think the fact that listdata.svc returns by default XML data rather than JSON might be the reason behind. I don;t know how to change it when create a dataview in the following code: Actually Ajax dataview Call use Json format as I discover this from Fiddler.



In fiddler, I can see listdata.svc get called, but it returns code 400, implying bad data format?
The problem was, url for fetchOperation in the code above ws illegal, and unfortunately this illegal url is tolerated in IE broswer.  Fiddle gave a misleading error code 400 due to whitespace.See Lessons learned from using Fiddler.

With this approach, http markup is clean without custom elements, and this is achieved by a custom item render as follow:









Related Posts:

Call Ajax-enabled WCF Service from Ajax JavaScript
Call WCF Service from Ajax JavaScript


Great Resources:

http://blogs.pointbridge.com/Blogs/monnette_jeff/Pages/Post.aspx?_ID=24

http://blogs.visoftinc.com/archive/2009/04/28/ASP.NET-4.0-AJAX-Preview-4-Client-Templates.aspx