This blog post describes how to add a Webpart in page using CSOM. The Webparts can be appended to a page using the Webpart XML content.

In SharePoint, it is represented by XML content. This can be extracted by exporting the Webpart from any page.

Source Code
  1. var wpSchemaXml = @"<?xml version='1.0' encoding='utf-8'?>
  2. <webParts>
  3. <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
  4. <metaData>
  5. <type name='Microsoft.Office.Server.Search.WebControls.ContentBySearchWebPart, Microsoft.Office.Server.Search,Version=16.0.0.0,Culture=neutral,PublicKeyToken=57e9bce111e7896d' />
  6. <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
  7. </metaData>
  8. <data>
  9. <properties>
  10. <property name='Title' type='string'>$Resources:Microsoft.Office.Server.Search,Title;</property>
  11. <property name='Description' type='string'>$Resources:Microsoft.Office.Server.Search,Description;</property>
  12. <property name='ChromeType'>None</property>
  13. <property name='AllowMinimize' type='bool'>true</property>
  14. <property name='AllowClose' type='bool'>true</property>
  15. <property name='Hidden' type='bool'>false</property>
  16. <property name='DataProviderJSON' type='string'>{'Properties':{'TryCache':true,'Scope':'{Site.URL}'},'PropertiesJson':'{\'TryCache\':true,\'Scope\':\'{Site.URL}\'}'}</property>
  17. </properties>
  18. </data>
  19. </webPart>
  20. </webParts>";
  21. var pageUrl = "/Pages/SearchResults.aspx";
  22. var zoneid = "Header";
  23. var zoneIndex = 1;
  24. Then USe this below code:
  25. var page = ctx.Web.GetFileByServerRelativeUrl(pageUrl);
  26. var wpm= page.GetLimitedWebPartManager(PersonalizationScope.Shared);
  27. var importedWebPart = wpm.ImportWebPart(wpSchemaXml);
  28. var webPart = wpm.AddWebPart(importedWebPart.WebPart,zoneid, zoneIndex);
  29. ctx.ExecuteQuery();
Conclusion

Was my blog helpful? If yes, please let me know and if not, please explain what was confusing or missing. I’ll use your feedback to double-check the facts, add info and update this blog.