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.
Similar articles
- Developing with Page Type Builder – Using Interfaces and Advanced Inheritance
- Page Type Builder 2 Preview 1 released!
- Developing with Page Type Builder – Getting Started
- A first stab at EPiServer CMS with ASP.NET MVC and Page Type Builder
- Dependency Injection with Page Type Builder 1.2
- Developing with Page Type Builder – Advanced Property Access
- How to create a custom EPiServer property
- Developing with Page Type Builder – Inheritance and Specifying Property Types
My book
Want a structured way to learn EPiServer 7 development? Check out my book on Leanpub!
Comments
comments powered by Disqus