Source: Dev4side Blog

Dev4side Blog How to insert an XsltListViewWebPart in a page of a SharePoint 2013 site via code

I'll leave you here a short piece of code, useful for inserting an XsltListViewWebPart via code within a web part page. I'm leaving you this because in order to insert this type of web part, we have to follow special steps. By exploring the properties of this web part, in fact, after an initial look, it would seem that it's sufficient to set the properties "ListId" and "ViewId" to specify the list from which to recover data and the mode of visualization. And yet, no! If we only set these two properties, the basic view from which all the SharePoint views start will be seen. The one with the fields "Title", "Modified" and "Modified by" I mean. So in order to have your view correctly configured within your XsltListViewWebPart type web part, it's necessary to lower the XML from the view to the property "XmlDefinition". Here's how: XsltListViewWebPart webpart = new XsltListViewWebPart(); webpart.ListId = list.ID; SPView view = list.DefaultView; webpart.ViewGuid = view.ID.ToString(); StringBuilder xml = new StringBuilder(); xml.Append( "<View Name=\"" + view.ID.ToString( "B" ).ToString().ToUpper(CultureInfo.InvariantCulture) + "\" MobileView=\"TRUE\" Type=\"HTML\" Hidden=\"TRUE\" DisplayName=\"\" Url=\"" + view.Url + "\" Level=\"255\" BaseViewID=\"1\" ContentTypeID=\"0x\" ImageUrl=\"/_layouts/images/generic.png\">" ); xml.Append( "<Query><OrderBy><FieldRef Name='FileLeafRef'/></OrderBy></Query>" ); xml.Append( "<ViewFields>" ); for ( int i = 0; i < view.ViewFields.Count; i++) xml.AppendFormat( "<FieldRef Name=\"{0}\"/>" , view.ViewFields[i]); xml.Append( "</ViewFields>" ); xml.Append( "<RowLimit Paged=\"TRUE\">10</RowLimit>" ); xml.Append( "<Toolbar Type=\"Standard\"/></View>" ); xml.Append( "<JSLink>clienttemplates.js</JSLink><XslLink Default=\"TRUE\">main.xsl</XslLink>" ); webpart.XmlDefinition = xml.ToString(); limitedWebPartManager.AddWebPart(webpart); The actual insertion within the page is done by using the AddWebPart method of the SPLimitedWebPartManager class, which you can instance by passing the URL of the web part page in which you want to insert the web part.

Read full article »
Est. Annual Revenue
$100K-5.0M
Est. Employees
1-25
CEO Avatar

CEO

Update CEO

CEO Approval Rating

- -/100