How to get the current SPS Area in a Web-Part

Tags: .NET, SharePoint

When we write a WebPart or WebControl that resides in a SPS Area, we will want to know at runtime which area we reside in.
This, surprisingly enough, is not trivial. It's not even easy. In fact, it's downright obscure

You can easily get the current SPWeb you're in using the SPControl object, but while the Area class can expose the underlying SPWeb, an SPWeb can't give you the equivalent Area - which makes sense, since SPS's Areas are built on top of WSS's SPWebs.

This data is stored quite nicely in the database - there's a WebCat table that cross-references Area GUIDs with Web GUIDs - but we really don't want to access the DB directly, do we?

The (obscure) solution is this:

From the Context property of the webpart/control, access the stored PageInfo object stored in the hashtable:

PageInfo pi = (PageInfo)Context.Items["SPS_PageInfo"];

The PageInfo class is defined in Microsoft.SharePoint.Portal.WebControls namespace, and is apprently undocumented in any SDK I found. It contains a property named CategoryID, which is the Guid of the current Area:

Guid currAreaGuid = pi.CategoryID;

Once we have the Guid, it's clear sailing all the way:

Area currArea = AreaManager.GetArea(PortalContext.Current, currAreaGuid);

And there was much rejoicing.

1 Comment

  • AvnerK said

    If I remember correctly, I've since learned that this is actually a roundabout way of getting this information. I think you can simply call AreaManager.GetArea(), passing it the the SPWeb.GetContextWeb().ID guid, and it will do the translation for you. I'm not entirely sure since it's been two years since I wrote this, but it's worth a try. :)

Comments have been disabled for this content.