This document describes how to create a page programmatically
in EPiServer CMS and
how to set 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:
C#
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:
C#
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
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:
C#
[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:
C#
StandardPage standardPage = contentRepository.GetDefault<StandardPage>(parent);
Now you have created an empty page under the specified parent page programmatically.
Note that there are other overloads of the GetDefaultPageData method that
can be used.
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:
C#
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:
C#
myPage.Property["MainBody"].Value = "<p>This is produced programmatically.</p>";
This is how you do it with a strongly typed model:
C#
standardPage.MainBody = "<p>This is produced programmatically.</p>";
You can publish the newly created page by calling the Save method of the DataFactory class:
C#
contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish);
Now a new page has been created and its MainBody property set, entirely through code.
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:
C#
contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);
Do you find this information helpful? Please log in to provide feedback.