I am creating a Provider Hosted App. USing the App, i would create a subsite.I want to add a Content Editor Webpart on the homepage of a newly created subsite using CSOM.

Can anyone suggest how to do this?

3 Answers 3


Check whether the below link can help you.



Any reason why you wouldn't created a Site Template that has the web part you need and then call that template from the app? I think that would be the best solution for you. Other than that you would have to create a feature stapler that would run after the site was created to then populate it with the CEWP.

  • could you please guide how do i do that in an O365 site
    – MJaiswal
    May 15, 2016 at 17:52

Here's an approach that I use - this code expects a well-formatted .webpart file that defines the web part you want to add to the page. Typically I create these files by adding the webpart to a page in my test environment and then exporting it, then moving that exported file to my VS solution and editing it if necessary.

This code also relies on the OfficePnP Core Library - https://github.com/OfficeDev/PnP-Sites-Core/tree/master/Core - which you should also be able to pull in via NuGet.

Final note... this is slightly modified to remove references to my actual solution so there may be a typo or two.

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Publishing;
using OfficeDevPnP.Core.Entities;
using OfficeDevPnP.Core.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml;   
using System.Xml.Linq;

public bool AddWebPartToPage(ClientContext ctx, string pageUrl, string webPartFileUrl, string wpTitle, string wpZone, int zoneIndex = 0)
  var pubPage = Web.GetPublishingPage2(pageUrl);

  WebPartEntity wpe = new WebPartEntity();
  wpe.WebPartTitle = wpTitle;
  wpe.WebPartZone = wpZone;

  ctx.Load(pubPage.ListItem, l => l.File);
  //Quick way to load the web part definition.
  var xmlDoc = new XmlDocument();
  wpe.WebPartXml = xmlDoc.OuterXml;

  wpe.WebPartIndex = zoneIndex;
  Web.AddWebPartToWebPartPage(pubPage.ListItem.File.ServerRelativeUrl, wpe);
  pubPage.ListItem.File.CheckIn("Added webpart", CheckinType.MajorCheckIn);
  return true;

You would want to call this function immediately after creating the subsite - if you're interested in how to create a subsite, please take a look at the OfficePnPDev.Core library - it has a helpful CreateWeb extension that simplifies things.

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.