EPiServer  /  CMS December 13, 2010

Strongly typed access to EPiServer’s Page Objects with Page Type Builder

While Page Type Builder doesn’t have any specific support for Page Objects at the moment it does have a neat little extension method for PageData that you can use to avoid using magic strings when working with Page Objects.

To illustrate this let’s look at an example that I’ve blatantly stolen from a post by Paul Smith:

PageData pageData = // Obtain the PageData instance to work with

PageObjectManager pom = new PageObjectManager(pageData);

Rating rating = pom.Load<Rating>("Rating");

if (rating != null)
{
    // Do something with the rating
}

In the example above an object of type Rating is retrieved for a page (the pageData variable). To do so we need to specify the name of the Page Object with a string (“Rating”).

If we are using Page Type Builder we can add a code property to those page types that should have a rating, like this:

[PageType]
public class Article : TypedPageData
{
    public Rating Rating { get; set; }
}

Assuming that we know that the type of the page we can then utilize Page Type Builders GetPropertyName method to replace the magic string:

Article pageData = (Article) // Obtain the PageData instance to work with

PageObjectManager pom = new PageObjectManager(pageData);

Rating rating = 
    pom.Load<Rating>(pageData.GetPropertyName(p => p.Rating));

if (rating != null)
{
    // Do something with the rating
}

Of course this means that we have a property in our page type class that doesn’t do anything, we only use it to retrieve it’s name. To fix that we can move the code for retrieving the Page Object into the property.

[PageType]
public class Article : TypedPageData
{
    public Rating Rating 
    {
        get
        {
             var manager = new PageObjectManager(this);

             return manager.Load<Rating>(
                 this.GetPropertyName(p => p.Rating));
        }
    }
}
With the Page Object retrieval stuff extracted our original code looks like this:
Article pageData = (Article) // Obtain the PageData instance to work with

if (pageData.Rating != null)
{
    // Do something with the rating
}

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more

Comments

comments powered by Disqus

My book

Want a structured way to learn EPiServer 7 development? Check out my book on Leanpub!

More about EPiServer CMS