Skip to content

Instantly share code, notes, and snippets.

@chrisobriensp
Last active March 12, 2017 10:56
Show Gist options
  • Select an option

  • Save chrisobriensp/30f45754080711d8e3d6b71945eee74c to your computer and use it in GitHub Desktop.

Select an option

Save chrisobriensp/30f45754080711d8e3d6b71945eee74c to your computer and use it in GitHub Desktop.
Adds a named SPFx web part to a SharePoint page - simple example with hard-coded values.
private static void addModernWebPartToPage(ClientContext siteContext)
{
Console.WriteLine(string.Format("addModernWebPartToPage(): Entered."));
// get page context - the actual name/page instance is specified in the Save() method..
ClientSidePage page = new ClientSidePage(siteContext);
// get the available web parts - this collection will include OOTB and custom SPFx web parts..
var components = page.AvailableClientSideComponents();
// name is actually the ID of the web part, based on the table elsewhere in this article..
string wpName = "daf0b71c-6de8-4ef7-b511-faae7c388708";
// add the named web part..
var webPartToAdd = components.Where(wp => wp.ComponentType == 1 && wp.Name == wpName).FirstOrDefault();
if (webPartToAdd != null)
{
ClientSideWebPart clientWp = new ClientSideWebPart(webPartToAdd) { Order = 10 };
page.AddControl(clientWp);
}
// the save method creates if not exists..
page.Save("COBModernPage1.aspx");
Console.WriteLine(string.Format("addModernWebPartToPage(): Leaving."));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment