Access Dynamic Properties when PageData is writable

One of the big changes between EPiServer CMS 4 and 5 is the handling of PageData instances and Dynamic Properties (read Inherited Property) in the cache. I was reminded of this when I created a custom property and needed access to a Dynamic Property but I always got a null value.

In EPiServer CMS 5 you will always get a read-only PagaData instance and if you want to modify it you have to call CurrentPage.CreateWritableClone() to get an instance that you can modify.

Read Dynamic Propety value returns null

On the read-only version you can always write CurrentPage[“MyDynamicProperty”] or CurrentPage.Property[“MyDynamicProperty”] to easily get hold of the inherited value. But if you try to do that on a writable PageData instance it will not work and you will always get null back.

In my case when I want the value of a dynamic property in a custom property controller it always returned null because in when you are editing the page your PageData instace is writable.

Using DynamicPropertyTree to FindDynamicProperty

You can retreive the value of a Dynamic Property with the same method that a read-only PageData use if you need it while modifying a page. 

PageReference locationRef = DynamicPropertyTree.Instance.FindDynamicProperty(“MyDynamicProperty”, CurrentPage.Property).Value as PageReference;

Change a Dynamic Property from code

If you need to change a Dynamic Property from code use the class EPiServer.DataAbstraction.DynamicProperty:

DynamicProperty myDynProp = DynamicProperty.Load(CurrentPage.PageLink, "MyDynamicProperty");
myDynProp.LanguageBranch = "sv"; //Only if you have unique values per languge
myDynProp.PropertyValue.Value = "My Value";

You will also find method like ListForPage(PageReference pageLink) that returns a list of all Dynamic Properties for a given page. DO NOT USE that method in when you just want to read a value! Use you PageData class instead for faster access.