Using ListData service in SharePoint 2010

For the past few weeks, I have been using ListData.svc, SharePoint Client object model and Jquery to create custom web parts which display some information from a list. First things first, ListData service reside in http:///_vti_bin/ListData.svc. So as an example, Let’s say that I have an employee list with First Name and Last Name columns. In order for me to get the list of employees from Employee list, the url would be http://samplesite/_vti_bin/ListData.svc/Employee.


var listUrl = 'http://samplesite/_vti_bin/ListData.svc/Employee';
$.getJSON(listUrl, function(data) {
   for (var i=0; i<data.d.results.length; i++)
   {
       var employee = data.d.results[i];
       alert(employee.FirstName);
   }
});

We can also filter the results that we would like to retrieve from the list by using the $filter query string or sort the results by using the $orderby. The example below filters the list by using the list item Id. For more information on what query strings that can be used, please have a look at this page in MSDN.

var listUrl = 'http://samplesite/_vti_bin/ListData.svc/Employee?$filter=Id eq 15';
$.getJSON(listUrl, function(data) {
   for (var i=0; i<data.d.results.length; i++)
   {       
   }
});

We can also use ListData service to create a new list item or update an existing item. Credits go to Anatoly Mironov for explaining on how to perform save and update operations. Following our example above, let’s say that we want to create an entry for a new employee

var newEmp = {};
newEmp.FirstName = "Joe";
newEmp.LastName = "Blogg";

var body = Sys.Serialization.JavaScriptSerializer.serialize(newEmp);

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            processData: false,
            url: listUrl,
            data: body,
            dataType: "json",
            success: function () { alert('succeeded');},
            error: function (xhr, status, error) { alert(xhr.responseText); }
        });
    }

Assuming that the create operation above succeeded and the new employee’s id is 20. We can update the employee list item as such

var emp = {};
emp.FirstName = "Joe";
emp.LastName = "B";

var body = Sys.Serialization.JavaScriptSerializer.serialize(emp);
$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            processData: false,
            headers: {
                "If-Match": "*",
                "X-HTTP-Method": "MERGE"
            },
            url: listUrl + "(20)",
            data: body,
            dataType: "json",
            success: function () { alert('succeeded');},
            error: function (xhr, status, error) { alert(xhr.responseText); }
        });

Notice the url and the headers for the AJAX call. The url that I specified points to the record that I just created and then I specified ‘MERGE’ to indicate that this is an update operation.