1
votes

I am using SharePoint online.
I want to use this CSOM code to add a WebPart to a page:

SP.File oFile = _web.GetFileByUrl(SiteUrl + "/SitePages/" + pageName);
oFile.CheckOut();
LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
var importedWebPart = limitedWebPartManager.ImportWebPart(webPartSchemaXml);
var webPart = limitedWebPartManager.AddWebPart(importedWebPart.WebPart, zoneid, zoneIndex);
oFile.Update();
await SiteCtx.ExecuteQueryAsync();
oFile.CheckIn(String.Empty, CheckinType.MinorCheckIn);

The problem is how to assign correct values to the zoneid string variable, which is the name of the Web Part zone to which to add the Web Part.

When I run this code nothing happens!
(it doesn't add the WebPart to the page and I am suspecting it is related to the wrong zoneId).

I have read various post, ranging from accessing the code behind of the .aspx page trying to find the WebPartZone, accessing the WebPartManager class (which should list the ZoneId's but I don't know how to get it, since that I am using the LimitedWebPartManager class).

I have tried various values for zoneId, but at the moment none of them work:

  • Zone 1 (just a guess!)
  • Zone 2 (i see it in the right tab when manually editing the webpart through Edit page)
  • Body (with this the code worked some days ago! but now it doesn't anymore)
  • Header
  • Left
  • Bottom

What is the proper method of findind zoneId's?

EDIT

The page is the homepage, I have read somewhere that it is a wiki page so maybe it has different ZoneId's.

1
Just to make sure: after running this snippet, did you invoke oFile.update() and executeQueryAsync() on the context?Szab

1 Answers

1
votes

ZoneIDs might be different depending on the page layout, but usually out-of-the-box SharePoint layouts use the following ID's for webpart zones:

  • TitleBar
  • Header
  • LeftColumn
  • MiddleColumn
  • RightColumn
  • Footer

Make sure that you invoke the update() method on your file object and executeQueryAsync() method on your context after importing the webpart - the latter function especially is responsible for sending the request to server and applying your changes.

Here's a nice article about adding webparts to pages programatically: How to programmatically add a ClientSide Web Part to a SharePoint page