1

I am simply trying to insert a web part to a page.

I ended up with this code:

using (_clientContext = new ClientContext(Url))
{
    _clientContext.Credentials = _credentials;
    var web = _clientContext.Web;

    var file = web.GetFileByServerRelativeUrl("/sites/test5/SitePages/Home.aspx");

    var limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
    var webPartDefinitions = limitedWebPartManager.WebParts;

    _clientContext.Load(webPartDefinitions);
    _clientContext.Load(limitedWebPartManager);

    _clientContext.ExecuteQuery();

    var webPartDefinition = limitedWebPartManager.ImportWebPart(_scriptEditorXml);
    var o = limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, "wpz", 0);
    _clientContext.Load(webPartDefinition);
    _clientContext.Load(o);

    _clientContext.ExecuteQuery();

}

But I can't see the web part on the page (it's a script editor).

However, when running this in the same context:

    foreach (var webpartDefinition in limitedWebPartManager.WebParts)
    {
        _clientContext.Load(webpartDefinition);
        _clientContext.Load(webpartDefinition, w => w.ZoneId);
        _clientContext.Load(webpartDefinition.WebPart);
        _clientContext.ExecuteQuery();

        Console.WriteLine($"{webpartDefinition.WebPart.ZoneIndex} - {webpartDefinition.ZoneId} - {webpartDefinition.WebPart.Title}");
    }

I can see all the web parts that I tried adding - so it seems they do exist somewhere, but they are not visible on the page at all. Output:

2 - wpz - Shared Calendar
1 - wpz - GroupTasks
3 - wpz - Recently Changed Items
2 - WebPartctl00_ctl33_g_c5595a9d_1cba_458d_9cc5_d06729f78715 - Script Editor
1 - WebPartctl00_ctl33_g_c5595a9d_1cba_458d_9cc5_d06729f78715 - Script Editor
0 - WebPartctl00_ctl33_g_c5595a9d_1cba_458d_9cc5_d06729f78715 - Script Editor
0 - WebPartWPQ3 - Script Editor
0 - MSOZoneCell_WebPartWPQ3 - Script Editor
0 - wpz - Script Editor

What is going on here?

  • Append ?contents=1 in the Page Url and check if web parts are open/closed on the page. – Nadeem Yousuf Feb 12 '18 at 4:36
  • @NadeemYousuf I see all the web parts on that page and they all have the "open on page" column set to "yes" – Bassie Feb 12 '18 at 4:42
  • Then make sure that page is checked-in and published – Nadeem Yousuf Feb 12 '18 at 4:43
  • @NadeemYousuf The page is checked in and published. I actually managed to do what I need using some other code, but I would like to know why my attempt posted here did not work. – Bassie Feb 12 '18 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.