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
In SharePoint, it is represented by XML content. This can be extracted by exporting the Webpart from any page.
Source Code
- var wpSchemaXml = @"<?xml version='1.0' encoding='utf-8'?>
- <webParts>
- <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
- <metaData>
- <type name='Microsoft.Office.Server.Search.WebControls.ContentBySearchWebPart, Microsoft.Office.Server.Search,Version=16.0.0.0,Culture=neutral,PublicKeyToken=57e9bce111e7896d' />
- <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
- </metaData>
- <data>
- <properties>
- <property name='Title' type='string'>$Resources:Microsoft.Office.Server.Search,Title;</property>
- <property name='Description' type='string'>$Resources:Microsoft.Office.Server.Search,Description;</property>
- <property name='ChromeType'>None</property>
- <property name='AllowMinimize' type='bool'>true</property>
- <property name='AllowClose' type='bool'>true</property>
- <property name='Hidden' type='bool'>false</property>
- <property name='DataProviderJSON' type='string'>{'Properties':{'TryCache':true,'Scope':'{Site.URL}'},'PropertiesJson':'{\'TryCache\':true,\'Scope\':\'{Site.URL}\'}'}</property>
- </properties>
- </data>
- </webPart>
- </webParts>";
- var pageUrl = "/Pages/SearchResults.aspx";
- var zoneid = "Header";
- var zoneIndex = 1;
- Then USe this below code:
- var page = ctx.Web.GetFileByServerRelativeUrl(pageUrl);
- var wpm= page.GetLimitedWebPartManager(PersonalizationScope.Shared);
- var importedWebPart = wpm.ImportWebPart(wpSchemaXml);
- var webPart = wpm.AddWebPart(importedWebPart.WebPart,zoneid, zoneIndex);
- 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.
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.

Join the conversation! Your thoughts help the community grow.