sharepoint-2013web-partscsom

Add custom web part to page SharePoint 2013 c# csom


I am trying to write c# code to add custom webpart programmatically to SharePoint 2013 page.

I tried searching net and stackoverflow but couldn't find any proper article or blog which can help me to achieve this.


Solution

  • You could use the the Webpart XML content to add a Webpart in page using CSOM, below is my sample for you. It's adding a document library to the page:

                var wpXML = @"<?xml version='1.0' encoding='utf-8' ?>
    <webParts>
      <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
        <metaData>
          <type name='Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
          <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
        </metaData>
        <data>
          <properties>
            <property name='ListUrl' type='string'>Shared%20Documents</property>
            <property name='MissingAssembly' type='string'>Cannot import this Web Part.</property>
          </properties>
        </data>
      </webPart>
    </webParts>";
    
                var page = ctx.Web.GetFileByServerRelativeUrl("/sites/test/SitePages/wiki1.aspx");
    
                var wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
                ctx.Load(wpm);
                ctx.ExecuteQuery();
    
                var importedWebPart = wpm.ImportWebPart(wpXML);
                var webPart = wpm.AddWebPart(importedWebPart.WebPart, "mainContent", 0);
                ctx.ExecuteQuery();