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.
This blog is built with EPiServer Community, EPiServer CMS, ASP.NET MVC and a bunch of other great products. The source code is available for download at the projects page, where you also can read more about this site and my other projects.
read more
Comments
Tom Stenius 1 years ago
Sweet! This is really nice. Never been fund of magic strings ;)
Niklas Melinder 1 years ago
Neat solution!
Daniel Berg 1 years ago
Nice!
Oskar Zetterberg 1 years ago
Excellent, a real neat solution.