How to Create a Publishing Page Programmatically in SharePoint 2013


Sathish Nadarajan
SharePoint MVP
Published On :   30 Mar 2015
Visit Count
Today :  3    Total :   15385
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

Sharegate: Kick-Ass Tool
Think Your SharePoint & Office 365 Are Secure ? Find Out Now!


In one of the Older Article, we saw how to create a publishing page using PowerShell. In the same manner, in this article let us see, how to create a publishing page using C#.

The actual requirement is, we need to develop an application Page and open it as a popup. From that popup, user can enter the title and url of the publishing page and clicks on the Create Page Button. We need to take values from the screen and based on the content type selected, we need to get the corresponding Page Layout and using that layout create the page.

The Input screen was something looks like

image

The Code Behind is like,

 protected void btnCreatePage_OnClick(object sender, EventArgs e)
         {
             try
             {
                 string currentSite = SPContext.Current.Site.OpenWeb().Title;
                 string strPageURL = txtURL.Text.Trim() + ".aspx";
                 string strPageTitle = txtTitle.Text.Trim();
                 string strCreatedPageURL = string.Empty;
                 string layoutName = GetLayoutName(ddlContentType.SelectedValue); 
                 SPSecurity.RunWithElevatedPrivileges(delegate()
                 {
                     using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
                     {
                         Microsoft.SharePoint.Publishing.PublishingSite oPublishingSite = new Microsoft.SharePoint.Publishing.PublishingSite(oSite);
 
                         SPWeb web = SPContext.Current.Site.OpenWeb();
                         web.AllowUnsafeUpdates = true;
                         Guid PagesID = web.Lists["Pages"].ID;
 
                         web.AllProperties["__PagesListId"] = PagesID.ToString();
                         //web.Update();
                         //web.AllProperties["__PublishingFeatureActivated"] = "True";
                         //web.Update();
 
                         Microsoft.SharePoint.Publishing.PublishingWeb oPublishingWeb = Microsoft.SharePoint.Publishing.PublishingWeb.GetPublishingWeb(web);
 
                         Microsoft.SharePoint.Publishing.PageLayoutCollection layoutCollection = oPublishingSite.GetPageLayouts(false);
 
                         Microsoft.SharePoint.Publishing.PageLayout layout = layoutCollection[layoutName];
 
                         Microsoft.SharePoint.Publishing.PublishingPage page = oPublishingWeb.GetPublishingPage(web.Url + "/Pages/" + strPageURL);
 
                         if (page == null)
                         {
                             page = oPublishingWeb.AddPublishingPage(strPageURL, layout);
                         }
                         else
                         {
                             throw new Exception("A page with the given URL already exists. Please try a different URL");
                         }
 
                         if (page.ListItem.File.CheckedOutByUser == null)
                         {
                             page.CheckOut();
                         }
 
 
                         page.Title = strPageTitle;
                         page.Update();
                         page.CheckIn("Page Created");
 
                          
                         //page.ListItem.File.Publish("Page Published");
 
                         web.AllowUnsafeUpdates = false;
                         strCreatedPageURL = web.Url + "/Pages/" + strPageURL;
                     }
                 });
                 
                 ClientScriptManager script = Page.ClientScript;
                 System.Text.StringBuilder sb = new System.Text.StringBuilder();
                 sb.Append(@"<script language='javascript'>");
                 sb.Append(@"CallBackSuccess('" + strCreatedPageURL + "');");
                 sb.Append(@"</script>");
                 script.RegisterStartupScript(this.GetType(), "JCall1", sb.ToString(), false);
             }
             catch (Exception ex)
             {
                 ClientScriptManager script = Page.ClientScript;
                 System.Text.StringBuilder sb = new System.Text.StringBuilder();
                 sb.Append(@"<script language='javascript'>");
                 sb.Append(@"CallBackFailure('" + ex.Message + "');");
                 sb.Append(@"</script>");
                 script.RegisterStartupScript(this.GetType(), "JCall1", sb.ToString(), false);
                 Logger.LogException("Error has occured on CreatePage Functionality and error message :: " + ex.Message, ex.StackTrace, "CreatePage", "btnCreatePage_OnClick", null);
             }
         }
 
         private string GetLayoutName(string contentTypeName)
         {
             string layoutURL = string.Empty;
             switch (contentTypeName)
             {
                 case "Article":
                     layoutURL = "/_catalogs/masterpage/CustomArticle.aspx";
                     break;
                 case "Convention":
                     layoutURL = "/_catalogs/masterpage/CustomConvention.aspx";
                     break;
                 
                 default:
                     layoutURL = "/_catalogs/masterpage/BlankWebPartPage.aspx";
                     break;
             }
 
             return layoutURL;
         }
 

The code was straight forward and we are calling a CallBackSuccess Method from the javascript.

This method is used to Open the page in Edit Mode. A simple piece of Javascritp is as follows.

 function OpenInEditMode(returnValue) {
     var temp = '?ControlMode=Edit' + '&amp;DisplayMode=Design'
     window.location.href = returnValue + temp;
 
 }
 
 

The extra Query strings which we need to pass are ControlMode and DisplayMode. This will open the newly created page in Edit Mode.

Happy Coding.

Sathish Nadarajan.

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

Protect Your SharePoint