Working with the ClientContext through multiple pages in a SharePoint cloud-hosted App

When I created my first Autohosted-App in SharePoint 2013, it contained only one page. Then I tried to add multiple pages and it was such a pain to work with the ClientContext through all the pages on my website. That’s because you receive the standard tokens only on the start page of your remote web.

To allow me working with the ClientContext on any page of my website, I created a small Helper that will manage the Client Context for me. Thus I don’t have to give the standard tokens in the Url of any links on my remote web.

First, be sure to have the TokenHelper.cs class in your remote web project, then you might add a new class named ContextHelper.cs

In my case the remote web is an ASP.NET MVC4 website, with this ContextHelper, I’m now able to use the ClientContext in every Action method of any Controller and I don’t have to give the Standard Tokens to every ActionLink (SPHostUrl, …) to be able to get the ClientContext.

Having this will store the context token and the host web in the session if the standard tokens are given in the Url. And when you’ll go to another action without giving the standard tokens in the Url, the context token and the host web will just be recovered from the session.

NB : You’ll have to call at least one time the GetClientContext method from the ContextHelper class in your start page Action, otherwise the standard tokens will not be saved in the session.

Using the REST api in a SharePoint-hosted App

This week-end, I’ve written a small “static class” in JavaScript (it works a bit like a List Generic Dao) to help me make CRUD operations on my lists in Sharepoint-hosted Apps.

Using the code above, it is now easier for me to create/read/update/delete items in any lists.

You’ll find a few samples below :

I know there is still place for improvement but it’s a start !