28 Oct 2010

SharePoint 2010 Static Web Part to read Page Properties

• Create a new page property by creating a new Site Column
• Edit the Page content type and add the new Site column
• Now all pages will have the new property to edit
• Create your web part to read the Page Property, like

try
{
if (SPContext.Current.Fields.ContainsField("Your Page Property Name") && SPContext.Current.Item["Your Page Property Name"] != null)
myString = SPContext.Current.Item["Your Page Property Name"].ToString();
}
catch { }

• Install and Deploy the web part on the server
• Find the public key token of your part by looking it up under c:\windows\assemblies
• Register the web part as static in your masterpage or page layout:

<%@ Register Tagprefix="Applicable" Namespace="ApplicableWebPartLib.TwitterBlock" Assembly="ApplicableWebPartLib, version=1.0.0.0,Culture=neutral,PublicKeyToken=2ee629bf628499ee" %>

• Use the web part on your page layout or master page:

<Applicable:TwitterBlock runat="server"></Applicable:TwitterBlock>

3 comments:

  1. This is an old post, but it looks like it addresses exactly what I need. I added a column to my page's content type, set it via properties and am now trying to access it from a custom webpart...

    Is making the webpart static a key part of this? I'm adding the webpart to a richhtml zone and am not making it static. When executing my webpart code, the field cannot be found even though you can see and set it in page properties.

    So I wonder if the webpart must be static for the properties to be available to C# or is there something else I'm doing wrong.

    Thanks!
    Russ

    ReplyDelete
  2. Sorry Russ, I haven't got an SP2010 instance around here to test with, but I don't think the webpart *had* to be static, it's just that's what I wanted in this case. Sorry I can't help you further. Could it be a permissions / publishing issue?

    ReplyDelete
  3. Wow, quick response!

    Seems odd that it'd be a permissions/publishing issue, but those cover so many reasons why things don't behave that it could be. I'll look down that path.

    Thanks!
    Russ

    ReplyDelete

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!