以编程方式创建包含webpart的webpart页面

时间:2011-12-08 08:58:37

标签: c# sharepoint web-parts

我想创建几个包含自定义Web部件的webpart页面(以编程方式)。 我搜索过互联网,但找不到任何我可以上班的东西。

到目前为止,这是我的代码(我创建了一个欢迎页面,而不是webpart页面):

using (SPSite site = new SPSite("http://v99-sp-public/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    PublishingSite pSite = new PublishingSite(site);
                    SPContentType ctype = pSite.ContentTypes["Welcome Page"];
                    PageLayoutCollection pageLayouts = pSite.GetPageLayouts(ctype, true);
                    PageLayout pageLayout = pageLayouts["/_catalogs/masterpage/welcomesplash.aspx"];
                    PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
                    PublishingPageCollection pPages = pWeb.GetPublishingPages();
                    PublishingPage pPage = pPages.Add("Klanten2.aspx", pageLayout);
                    SPListItem newpage = pPage.ListItem;
                    newpage["Title"] = "Klanten";

                    newpage.Update();

                    newpage.File.CheckIn("Checkin");
                    newpage.File.Publish("Publisch");
                 }
              }

请帮帮我,

感谢。

2 个答案:

答案 0 :(得分:3)

您可以使用SPLimitedWebPartManager和您的webPart定义网址添加webpart。这个例子可以帮助你入门:

XmlTextReader reader = new XmlTextReader(new StringReader(web.GetFileAsString(<Url to your .webpart file here>)));

SPLimitedWebPartManager wpm = web.GetLimitedWebPartManager(<URL to your page>, Syste.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

WebPart wp = (WebPart) wpm.ImportWebPart(reader, out errMsg);
wp.Title = "My Title for this webpart";

wpm.AddWebPart(wp, <Name of WebpartZone here, e.g. "Header">, <Zone Index here>);
wpm.SaveChanges(wp);

填写空白后,此代码会在您的发布页面上放置一个WebPart。最后,当您为发布页面实例化WebPart管理器时,最重要的功能是SPLimitedWebPartManager.ImportWebPartSPLimitedWebPartManager.AddWebPart

答案 1 :(得分:0)

好的,做了一点挖掘......这是我的解决方案。

using(SPSite site = new SPSite("http://my.dev.com"))
{
    using(SPWeb web = site.OpenWeb())
    {
        SPFile page = web.GetFile("SitePages/Welcome.aspx");
        using(SPLimitedWebPartManager manager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
        {
            string errMsg = string.Empty;
            SPFile myWebPart = web.GetFile("_catalogs/wp/myWebPart.webpart");
            XmlTextReader read = newXmlReader(myWebPart.OpenBinaryStream());
            var wp = manager.ImportWebPart(read, out errMsg);
            manager.AddWebPart(wp, "<Webpart Zone>", 1);
            manager.SaveChanges(wp);
        }  
    }
}