Manipulating an EPiServer Page Programmatically

Creating a Page

Here’s how you can create a page in code from a page type you’ve already defined.

First create a new instance of the page type under another page in the form of a link:

var newBlogPost = ContentRepository.GetDefault<BlogPostPage>(parentLink);

Then set whatever properties you wish to the newBlogPost object.

newBlogPost.Subject = "Creating an EPiServer Page Programmactically";
newBlogPost.Content = "Meta";

Finally call the Save method on EPiServer’s content repository.

ContentRepository.Save(newBlogPost, SaveAction.Publish)


Updating a page

The structure to updating a page is thankfully very similar to creating one.

Load the page you wish to update from the Content Repository. 5 is the id of the page.

var contentReference = new ContentReference(5)
ContentRepository.Get<BlogPostPage>(contentReference);

Create a writeable clone of the update. This allows you to update it’s properties:

var clone = (BlogPostPage)page.CreateWritableClone();

Update a properties of the cloned page

clone.Subject = "Creating an EPiServer Page Programmactically";

Call the Content Repository to Save the page and public it at the same time:

ContentRepository.Save(clone, SaveAction.Publish);


Troubleshooting

When creating a new page and / or block you may get the following exception:

The INSERT statement conflicted with the FOREIGN KEY constraint 'FK_tblContent_tblContentType'. The conflict occurred in database ' ', table 'dbo.tblContentType', column 'pkID'.

This commonly gets throw when there are two developers working against the same database but have different versions of the page / block you are trying to save.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s