SharePoint Online has this awesome functionality where you click on the Page>Edit>Insert and are able to add an existing list as a web part to the home page.
I am trying to implement the same functionality using CSOM, but there seems to be no such option OOTB. What I have so far:
File page = ctx.Web.GetFileByServerRelativeUrl("/sites/powie64/SitePages/Pageee.aspx");
LimitedWebPartManager wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
ctx.Load(wpm);
ctx.Load(wpm.WebParts);
ctx.ExecuteQuery();
string xml = ctx.Web.Lists.GetByTitle("Sample List").SchemaXml;
wpm.ImportWebPart(xml);
ctx.ExecuteQuery();
Console.ReadKey();
- LimitedWebPartManager does not seem to have any function "AddFromList." That leaves me with AddWebPart() or ImportWebPart().
- Adding WebPart requires adding a ready web part. Lists, even though in UI they are visible in the Web Part Tab, are not listed under site webparts:
code
foreach (WebPartDefinition wp in wpm.WebParts)
{
ctx.Load(wp.WebPart);
ctx.ExecuteQuery();
Console.WriteLine(wp.Id+" "+wp.WebPart.Title+" "+wp.WebPart.TitleUrl+" "+wp.WebPart.ZoneIndex+" ");
}
- For importing a webpart, we need XML, but List SchemaXML is different from Xml required for a webpart, e.g. here, so direct copy paste is not possible.
Could you please advise how to tackle it? The lists are pretty simple and I do not need to convey almost any settings, just the overview, but it's a lot of lists per web, and 70 subsites per site collection.
EDIT
The edit is additional information to the comment on Rob Windsor's answer:
This is the XML I am using:
static string xemelek = "<?xml version='1.0' encoding=\"utf-8\"?><webParts><webPart xmlns='http://schemas.microsoft.com/WebPart/v3'><metaData><type name='Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' /><importErrorMessage>Cannot import this Web Part.</importErrorMessage></metaData><data><properties><property name='ListUrl' type='string' /><property name='ListId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>757981FB-184A-441B-952D-9434BE33DC85</property><property name='ListName' type='string'>{757981FB-184A-441B-952D-9434BE33DC85}</property></properties></data></webPart></webParts>";
EDIT 2
Adding working code to close the question:
WebPartDefinition newWebiie= wpm.ImportWebPart(xemelek);
WebPartDefinition webpartie = wpm.AddWebPart(newWebiie.WebPart, "mainContent", 0);
ctx.Load(newWebiie);
ctx.ExecuteQuery();