Question

I would like to add a couple of libraries as web parts in the wiki page "SitesPages/Home.aspx" using CSOM in SharePoint Online.

Can anyone tell me how can I do that? An example will be very helpful.

I found this blog, and it inserts a web part to a web part page. I would like to insert it in a wiki page. And another thing with this code is using xml as web part.

Was it helpful?

Solution

Check this https://stackoverflow.com/questions/27268492/how-to-add-a-web-part-into-a-sitepages-home-aspx-using-csom

public static void AddWebPartIntoWikiPage(ClientContext context, string pageUrl, string webPartXml)
{
        var page = context.Web.GetFileByServerRelativeUrl(pageUrl);
        var webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);

        var importedWebPart = webPartManager.ImportWebPart(webPartXml);
        var webPart = webPartManager.AddWebPart(importedWebPart.WebPart, "wpz", 0);
        context.Load(webPart);
        context.ExecuteQuery();

        string marker = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>", webPart.Id);
        ListItem item = page.ListItemAllFields;
        context.Load(item);
        context.ExecuteQuery();
        item["PublishingPageContent"] = marker; 
        item.Update();
        context.ExecuteQuery();
}

Usage

var webPartXml = System.IO.File.ReadAllText(filePath);
using (var ctx = new ClientContext(webUri))
{
    AddWebPartIntoWikiPage(ctx, wikiPageUrl,webPartXml);
}

Wiki pages do not have zones; web parts are placed inline with the text content. could programmatically reference the tags in your Wiki Page content.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top