Friday, July 20, 2012

SPContext in SharePoint 210

Before discussing what SPContext is, we need to understand what a Context is.
As stated by free dictionary, context means :The circumstances in which an event occurs.
So if we take things in context and try to dig deeper in SPContext in SharePoint 2010 or any other version, it represents a context of your HTTP Request in Microsoft SharePoint Foundation.

SPContext object is used in your custom code like custom web parts and it returns context information in which your code is running.

For example you need to read some items from a list. There are 2 ways to do it. Either hard code the url to get to your Web Application/Site Collection/List or use SPContext to get the required object and use it accordingly.

Once you deploy your custom webpart in your web application and try to use it on a page, this site/site collection/web application becomes your context because your code in running inside this context.

The most important members of SPContext is Current
Once you get current context, you can use further members of the class

SPWeb web = SPContext.Current.Web;
SPSite site = SPContext.Current.Site;
SPList list = SPContext.Current.List;
SPListItem listItem = SPContext.Current.Item;

One important thing is that it is also available in SandBoxed solutions

Related Links

No comments: