Create Modern page using C# in SharePoint’19 on-prem

Here I am just demonstrating to you, how we can create a page using the server object model in SharePoint’19 on-prem. There are many things we control through C# while creating the Pages like disable comment, publish the page, custom templates, embedded pre-defined web part, and many more.

There are three types of Page Layout available, so you can choose based on your requirement. By default, you can only create Article Page from UI, but after doing some customization you can do much more on pages.

  • Home
  • Article

Another parameter is “PromotedState”, if you pass 2 then your page is a news page and 0 generic pages.

We can also use customize canvas or we can say multiple page templates to create the Modern page. By default on the team site, the Page template option is not available so you can achieve it through us this small customization.

Refer article: Create modern page using defined template

string PageLibName = "Site Pages";
string PageName = "demo-page.aspx";
SPUser PageAuthor = "<Pass SPUser Object>";
string SiteURL = "<Pass Site URL>";
using (SPSite oSPsite = new SPSite(SiteURL))
{
    using (SPWeb oWeb = oSPsite.OpenWeb())
    {
        SPList oList = oWeb.Lists[PageLibName];
        SPListItem oItem = oList.RootFolder.Files.Add(String.Format("{0}/{1}", oList.RootFolder.ServerRelativeUrl, PageName), SPTemplateFileType.ClientSidePage).ListItemAllFields;
        oItem["Title"] = System.IO.Path.GetFileNameWithoutExtension(PageName);
        oItem["ContentTypeId"] = "0x0101009D1CB255DA76424F860D91F20E6C4118";
        oItem["ClientSideApplicationId"] = "b6917cb1-93a0-4b97-a84d-7cf49975d4ec";
        
        //Home
        oItem["PageLayoutType"] = "Article";

        //Promoted State 2 is for News and 0 for Generic Page
        oItem["PromotedState"] = 2;

        //comment below if you don't want to change page author or editor -- Created by and Modfied by field
        oItem[SPBuiltInFieldId.Author] = oWeb.EnsureUser(PageAuthor.LoginName);
        oItem[SPBuiltInFieldId.Editor] = oWeb.EnsureUser(PageAuthor.LoginName);
        
        //this is also key factor while create the page , you can change it if you want custom page layout. 
        oItem["CanvasContent1"] = "<div> </div>";

        //False to enable comment and True if you wanted to disable the comment 
        oItem.SetCommentsDisabled(false);
        oItem.Update();
    }
}