How to Create a Page Programmatically

Here we shall demonstrate how to create a page programmatically and set the MainBody property. Decide where you want your new page published in the structure of the Web site. 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:

CopyC#
PageReference parent = PageReference.StartPage;

Next we are going to create a new empty page with default values according to the property settings of its page type. We do this by specifying the parent under which to create the page and by specifying the name of the page type to use:

CopyC#
PageData myPage = EPiServer.DataFactory.Instance.GetDefaultPageData(
                      parent, "Standard page");

We have now created an empty page under the specified parent page programmatically.

Please note that there are other overloads of the GetDefaultPageData method that can be used.

Now we have to specify our page property values before publishing the page.

In the code example below we define some standard property values - the page name and the URL segment:

CopyC#
myPage.PageName = "My new page";
myPage.URLSegment = EPiServer.Web.UrlSegment.CreateUrlSegment(myPage);

In the code example below we define the user defined property MainBody:

CopyC#
myPage.Property["MainBody"].Value = "<p>This is produced programmatically.</p>";

Finally we can publish the newly created page by calling the Save method of the DataFactory class:

CopyC#
DataFactory.Instance.Save(myPage, EPiServer.DataAccess.SaveAction.Publish);

Now a new page has been created and its MainBody property set - entirely through code.

Please note that the above method call requires that the current user has the proper permissions to publish a page in this location. This may cause a problem if the current user is an anonymous user and you still want the page to be published programmatically. In this situation you may use another overload of the Save method to permit the publishing; even if the current user does not have the necessary permissions:
CopyC#
DataFactory.Instance.Save(myPage, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);