How to Create a Page Programmatically in Episerver?

There are numerous scenarios when you need to create a page in code rather than the editor, say content migration from an old CMS into EPiserver. Adding pages in Episerver is, luckily, very easy using the IContentRepository. The first thing you need to do is check that a page with the same name doesn't exist. For this example, I'm going to create all my pages under the StartPage but you can add them anywhere you want.

   var pageName = "New Page";

    var repository = ServiceLocator.Current.GetInstance<IContentRepository >();
    var existingContentPage = repository.ContentRepository
                .FirstOrDefault(x => x.PageName == pageName);

If you do not do this then you will get an error when you save so it's worth checking. Next up is setting up your properties:

    var repository = ServiceLocator.Current.GetInstance<IContentRepository >();
    var contentPage = repository.ContentRepository.GetDefault<ContentPage>(ContentReference.StartPage);

    contentPage.Name = "Example Page";
    contentPage.MainContentArea = new ContentArea();


The first thing we do is create a default empty page using the GetDefault method in IContentRepository. We simply tell Episerver the type of page we want to create and where we want to create it. Next we assign values to the properties we are interested in. Lastly, we pass the page into IContentRepository save method.


That's all there is to saving a page programmatically in code. You create a default type specifying the parent of where you want it to be created, you fill in the properties you care about and then you save it back to the database. On word of caution is to remember to check if a page with the same name already exists.. otherwise you will start to get some unexpected exceptions

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top