I’m currently working with a client who is using Publishing pages to host a number of custom Web Parts on their page. A number of these web parts need information from an external SQL database. My customer asked me if there was a way for the information to be accessed once, and for all the Web Parts to consume that information.

There is, in fact, an easy way to do this, using good ol’ ASP.NET.

First, create a class (I’ll call mine BasePageLayout) that inhertis from Microsoft.SharePoint.Publishing.PublishingLayoutPage. Then, create a public property with the value you want to access. As an example, let’s create a property called ProductId. Then, override the OnInit() method of the page and place your code inside that accesses the product ID. Once you have the product ID, assign it to the public property you created. Your new class might look like this:

using System;
using Microsoft.SharePoint.Publishing;

namespace BeckyBertram.PageLayouts
{
    public class BasePageLayout : PublishingLayoutPage
    {
         private int productId;
         public int ProductId
         {
             get { return productId; }
             set { productId = value; }
         }

         protected override void OnInit(EventArgs e)
         {
               //Add code here to get ProductId.
              productId = GetProductId();
              base.OnInit(e);         
         }
    }
}

Next, create a class that your particular Page Layout will use. Your new class will not inherit from PublishingLayoutPage, but from your new BasePageLayout. Your new class might look like this:

using System;
namespace BeckyBertram.PageLayouts
{
    public class MyPageLayout : BasePageLayout
    {
    }
}

Next, wire up your Page Layout markup page with its code-behind, by passing in the type and assembly information in the page directive, like this:

<%@ Page language="C#" Inherits="BeckyBertram.PageLayouts.MyPageLayout, BeckyBertram.PageLayouts, version=1.0.0.0,Culture=neutral,PublicKeyToken=cd26d92ca3528a2b" %>

Now, inside your Web Part’s code, (such as in the Page_Load method), you can access the PropertyId property of your BasePageLayout class, like this:

int productId = ((BasePageLayout)this.Page).ProductId;