SharePoint 2013: Paging with SharePoint Client Object Model
Introduction:
Paging list items in Client object model in SharePoint is very essential to ensure proper performance & usability for your custom application; although there are a lot of good resources on implementing paging on the server side; I have not seen any full & easy to follow tutorial about paging with SharePoint on client side, so let us start!
What is paging?
Generally speaking; Paging is getting items from a SharePoint list in a chunks instead of getting them all in one shot, this chunk is controlled by two variables:
- Page size: number of items to be displayed.
- Page position: current index; in other words; in which page we are right now.
Getting items:
To get items from the list, you need to call getItems() function with proper SP.CamlQuery() object:
var context = SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle("ContactsList");
var spItems = list.getItems(camlQuery);
So paging is all about preparing this magical object "camlQuery" of type SP.CamlQuery() and passing it to getItems() Function.
Pages size:
camlQuery object defines a lot of things, but in our case; we are interested in page size & page position.
Setting page size is quite easy, see how easy it is: (here we set the page size to 4)
camlQuery.set_viewXml("<View>" +
"<ViewFields>" +
"<FieldRef Name='FirstName'/>" +
"<FieldRef Name='Title'/>" +
"<FieldRef Name='Company'/>" +
"</ViewFields>" +
"<RowLimit>4</RowLimit></View>");
Page Position:
Setting the position is little bit challenging so here we go:
camlQuery.set_listItemCollectionPosition(position);
Ok, so what is position?? Here it is:
var position = new SP.ListItemCollectionPosition();
position.set_pagingInfo(pageInfo);
OK, so what is the pageInfo?? Let us have a deep look here.
pageinfo is a special string which should be passed as the following diagram:
Try to stare for one minute in the above picture, did you get it!
let me explain it; For example, let us assume that we are now on page 2:
If we click on <Back button; we need to pass PagePrev=True&Paged=TRUE&p_ID=5; this simply tells SharePoint "I need the previous X items that precede (come before) the item with ID 5" (where X is the page size)
If we click on Next> button; we need to pass Paged=TRUE&p_ID=8; this simply tells SharePoint "I need the next X items that come after the item with ID 8" (where X is the page size)
As you can see; the existence of PagePrev=TRUE tells SharePoint which direction we are going (backward or forward),p_ID=5 is simply the item id; Paged=TRUE existence is a must in both back & next; but nobody knows why :-)
Complete picture:
There are some considerations that you need to pay attention to like sorting & filtration; to make sure that you get the full story; Muaiwyah Shannak did a great job in providing a source code for all these functionalities here.
Download the source from here.