如何用代码的方式添加一个WebPart到发布页中
有时候我们可能需要用代码添加一个WebPart到发布页中,这时候我们可以使用这种方法来实现
using (SPSite objsite = new SPSite(SPContext.Current.Site.ID)) { PublishingWeb pweb = PublishingWeb.GetPublishingWeb(objsite.RootWeb); XmlTextReader reader = new XmlTextReader(new StringReader(objsite.RootWeb.GetFileAsString(pweb.Url + "/_catalogs/wp/VisualWebPart1.webpart"))); SPFile objpage = objsite.RootWeb.GetFile("Pages/TestWebpart.aspx"); if(objpage.CheckOutType == SPFile.SPCheckOutType.None) objpage.CheckOut(); SPLimitedWebPartManager objWebPartManager = objpage.GetLimitedWebPartManager(PersonalizationScope.Shared); VisualWebPart1 objwebpart = new VisualWebPart1(); objwebpart.Title = "Added programatically"; objWebPartManager.AddWebPart(objwebpart, "CenterColumn", 0); objpage.CheckIn(string.Empty); objpage.Publish(string.Empty); }
上面的参数说明
| VisualWebPart1.webpart | 在新建一个可视化Webpart的时候会自动生成,根据你使用的名字命名 |
| TestWebpart.aspx | 发布页的地址 |
| CenterColumn | 发布页中的WebPartzone的id |
注:
页面中没有WebPartZone的就不能使用此方法添加
参考:
http://sharepoint2010mind.blogspot.hk/2012/06/add-webpart-programmatically-publishing.html
欢迎转载 Please via @Michael Thanks!
Focus in SharePoint
Focus in SharePoint
浙公网安备 33010602011771号