Thursday, April 10, 2014

SharePoint 2013 Client-Side Object Model (CSOM) get list items

The client-side object model (or CSOM) which has been available since SharePoint 2010 provides a strong framework for working with SharePoint on the client side. Instead of synchronous calls in server side C# code which can take time and affect the user experience, asynchronous calls can be made client-side which can be quicker and provide a better user experience.
var clientContext = new SP.ClientContext("/");
var web = clientContext.get_web();
var list = web.get_lists().getByTitle("List Name");
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'FieldName\'/><Value Type=\'Text\'>X</Value></Eq></Where></Query></View>');
var items = list.getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(functionSuccess(), functionFailure);
The code above runs CAML query on a SharePoint list and makes an asynchronous call to return the data. If the data is returned successfully a "success function" is run, otherwise the "failure function" is run.