SharePoint 2013: Moving webparts programmatically to rich content zone

Moving or adding webparts programmatically in SharePoint should not be a big thing, there are built-in methods to move webparts using the LimitedWebPartManager in the server side object model. Unfortunately, this only works for regular webpartzones. As soon as you try to move a webpart to a rich content area, SharePoint turns into a massive black hole, hiding the webparts you tried to move. You can still see them if you add a “?contents=1” to your url, but they will not render on a regular request.

There’s a nice article written by Waldek Mastykarz on how to handle this in SharePoint 2010. Although it’s a great article which gives you alot of information, it’s not going to work in SharePoint 2013. Analyzing the generated HTML markup helped me alot to resolve the problem. I thought it might be a good idea to share some lines of my code, hopefully it will save you some time.

			using (SPLimitedWebPartManager limitedWebPartManager = 
						publishingPage.ListItem.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
            {
                //get all webparts
				SPLimitedWebPartCollection webPartCollection = limitedWebPartManager.WebParts;
                    
                //move webparts
                int targetZoneIndex = 0;
                foreach (Microsoft.SharePoint.WebPartPages.WebPart webPart in webPartCollection)
                {
					//hardcoded rich content zone, you might use a mapping table in a live environment
					string newTargetZoneId = "wpz";

					limitedWebPartManager.MoveWebPart(webPart, newTargetZoneId, targetZoneIndex++);
					limitedWebPartManager.SaveChanges(webPart);

					//if targetzone is a rich content field, add a webpart container to it
					if (newTargetZoneId == "wpz")
					{
						string htmlcontent = String.Format(CultureInfo.InvariantCulture,"<div class="ms-rtestate-read ms-rte-wpbox" contenteditable="false"><div class="ms-rtestate-notify  ms-rtestate-read {0}" id="div_{0}"></div><div id="vid_{0}" style="display:none;"></div></div>", new object[] { webPart.StorageKey.ToString("D") });
						SPListItem item = publishingPage.ListItem;
						string content = item["PublishingPageContent"] as string;
						item["PublishingPageContent"] += htmlcontent ;
						item.Update();
					}

					publishingPage.PublishingWeb.Update();
                }
            }
Advertisements
SharePoint 2013: Moving webparts programmatically to rich content zone

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s