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 .GetChildren<ContentPage>(ContentReference.StartPage) .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(); repository.ContentRepository.Save(contentPage, SaveAction.Publish, AccessLevel.NoAccess);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.