Modify and publish a page programmatically

by: Ted Nyberg (Hallvarsson & Halvarsson)

Inspired by Marek's post on modifying existing pages I  decided to complement my post on programmatically publishing new pages with a post on how to modify and publish existing pages in EPiServer.

1. Why you can't modify a PageData object

As Marek points out in his post, EPiServer will always return read-only versions of PageData objects for performance:

//Retrieve a read-only version of a page
PageReference myPageRef = new PageReference(1);
PageData myPage = DataFactory.Instance.GetPage(myPageRef);


Derived methods for fetching pages yield the same result, such as the GetChildren() method. So, we would get an exception if we tried this:

myPage.PageName = "My modified page"; //Exception thrown


This is because it is much faster for EPiServer to fetch read-only versions from the database or page cache. So, we need a different approach in order to modify our existing pages.

2. Get a writable page version to edit

Before we can modify and re-publish an existing page we need to get a writable version of the page. This is accomplished by calling the CreateWritableClone() method of a PageData object:

//Get a writable PageData object to modify
PageData myWritablePage = myPage.CreateWritableClone();


Now we can edit the values of our page properties:

Property["MainBody"].Value = 
   "<p>This content was updated.</p>";

3. Publish your modified page

Once we've updated our page properties we can save and publish the new page through code by calling the Save method of the DataFactory class:

//Perform 'Save and publish' programmatically
DataFactory.Instance.Save(myWritablePage, SaveAction.Publish);


Make sure to also check out my post on creating a page programmatically!

06 March 2008


Comments

  1. You made a very good example, thank you! Could you please advise me why it may not work? I'm trying to test your idea in the developping environment of the 5th version. I'd like to use my own content creating/editing visual interface (a simple aspx-form with a set of ) instead of the Edit-mode) and using your approach I only get a set of different versions with the same original (i.e. unchanged) content of the page.
Post a comment    
User verification Image for user verification  
Ted Nyberg (Hallvarsson & Halvarsson)

About me

I'm a consultant with the corporate communications consultancy Hallvarsson & Halvarsson, part of the transatlantic stakeholder management and financial communications firm Sage Holdings.

My focus areas include web applications, intranets, and corporate websites.

Live Messenger

Hallvarsson & Halvarsson logo
 MCPD, MCTS and MCP logos

Bloggtoppen.se


Syndications


Archive


Tag cloud

EPiTrace logger