Thursday, September 29, 2005

Extreme SharePoint Design: 'Go Back To [Area/Site]' Link

The ability to call pages in the /_layouts/1033/ directory is very convenient; all the administration pages can be stored in one location and referenced from any area or site within the portal. SharePoint uses the SPControl.GetContextWeb(Context) and SPControl.GetContextSite(Context) functions to determine what context the user is in when a page is called, then presents the appropriate content. Pretty slick.

There's just one problem: when accessing these pages, users often get lost with no way to return to where they came from. Nothing is more frustrating than finding yourself seven steps into a wizard with no way to bail out but to smack the 'Back' button repeatedly. The solution is a 'Go Back To [Area/Site]' link at the top of each administration page which gives the user one-click access to the place they started from.

Insert the following code into AlternateHeader.aspx or directly into your administration pages just after the PageHeader section (if you're using heavily customized Site Definitions as I often do, most of your admin pages will have header code in them to overwrite AlternateHeader and PortalHeader; just paste the following code into the appropriate section and format it as needed):

<%
try
{
Response.Write ("<a href='" + SPControl.GetContextWeb(Context).Url + "'>Go Back to " + SPControl.GetContextWeb(Context).Title + "</a>");
}
catch
{Response.Write ("Portal Administration Page");
}
%>

The 'try' block creates a link back to the root of the referring area/site using the title field as the link text. The 'catch' block writes out a general statement that you can replace with anything you like, just in case the link fails to render properly.

NOTE: In 'Extreme SharePoint Design: Creating Custom User Menus', I used the same function to replicate the behavior of the 'Home' button on WSS sites. Use SPControl.GetContextWeb(Context) anytime you want to refer to the root URL of an area or site; use SPControl.GetContextSite(Context) to reference the site collection the current site belongs to.

UPDATE: I forgot to mention that you'll need to insert the following code at the top of alternateheader.aspx in order for SharePoint to parse inline code blocks on the page (otherwise you will receive the dreaded 'External component has thrown an exception' error):

<%@ Page language="C#" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>