Creating a Page Programmatically
Introduction
This document describes how to create a page programmatically in EPiServer CMS and how to set the MainBody property.
Example
Decide where you want your new page published in the structure of the website. This is accomplished by specifying a PageReference object pointing to the desired parent page, such as the start page as in the following code line example:PageReference parent = PageReference.StartPage;
Create a new empty page with default values according to the property settings of its page type. You do this by specifying the parent under which to create the page and by specifying the name of the page type to use:
IContentRepository contentRepository = Locate.ContentRepository();
IContentTypeRepository contentTypeRepository = Locate.ContentTypeRepository();
PageData myPage = contentRepository.GetDefault<PageData>(parent, contentTypeRepository.Load("Standard page").ID);
You can also use a strongly typed model. Given that you have created a model that looks like this:
[ContentType]
public class StandardPage : PageData
{
public virtual string MainBody { get; set; }
}
Now you can use the generic overload of GetDefaultPageData to achieve the same as the above example:
StandardPage standardPage = contentRepository.GetDefault<StandardPage>(parent);
Now you have created an empty page under the specified parent page programmatically.
You should also specify your page property values before publishing the page.
The code example below shows how to define the standard property values page name and the URL segment:
myPage.PageName = "My new page";
myPage.URLSegment = EPiServer.Web.UrlSegment.CreateUrlSegment(myPage);
The code example below shows how to define the user defined property MainBody:
myPage.Property["MainBody"].Value = "<p>This is produced programmatically.</p>";
This is how you do it with a strongly typed model:
standardPage.MainBody = "<p>This is produced programmatically.</p>";
You can publish the newly created page by calling the Save method of the DataFactory class:
contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish);
Now a new page has been created and its MainBody property set, entirely through code.
contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);
Last updated: Mar 25, 2013