Wednesday, May 21, 2014

Get SharePoint list properties using JavaScript Object Model

Introduction

I was developing a SharePoint App using SharePoint JavaScript Object Model which also called SharePoint ECMAScript Client Object Model. Today I will show how to retrieve basic properties from SharePoint list.

Solution

  1. function getSPListProperties() {
  2.  
  3.           //Get the current context. Same as SPContext in server side
  4.           var ctx = SP.ClientContext.get_current();
  5.  
  6.           //Get the web
  7.           var web = ctx.get_web();
  8.  
  9.           //Get the list by its title
  10.           var list = web.get_lists().getByTitle('Title of the List Instance');
  11.  
  12.           //Load the properties which we need
  13.           ctx.load(list, 'Title', 'Id', 'Created', 'ItemCount');
  14.  
  15.           //Excecute the loded queries asyncronisly
  16.           ctx.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
  17.  
  18.           //Success method
  19.           function onQuerySucceeded() {
  20.               alert(list.get_title());
  21.               alert(list.get_id());
  22.               alert(list.get_created());
  23.               alert(list.get_itemCount());
  24.           }
  25.  
  26.           //Falied method
  27.           function onQueryFailed() {
  28.               alert('failed');
  29.           }
  30.       }

 

Conclusion

Please note that when you get the list through the method web.get_lists().getByTitle('Title of the List Instance'); It doesn’t load all the properties like in server side. We have to explicitly load the properties which we need.
When you didn’t load for a property, and try to call the method in order to get the data it will throw an exception.
Capture
Reference:
http://msdn.microsoft.com/en-us/library/office/jj245759(v=office.15).aspx#constructors

No comments:

Post a Comment