Programmatically Create publishing page sharepoint 2010
The code below will add a new publishing page and will check it in so that gets visible to the users. To do this you will need to reference Microsoft.SharePoint.Publishing in your project.
Code snippet :
using(PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web))
{
PageLayout myLayout = pWeb.GetAvailablePageLayouts()["Page Layout Name"];
PublishingPage newPage = pWeb.GetPublishingPages().Add("NewPage.aspx", myLayout);
newPage.Update(); // commit to the database
}
// apply the HTML properties
SPFile file = web.GetFile(newPage.Url);
SPListItem item = file.Item;
item["Title"] = "New Page Title";
item["Page Content"] = "
item.Update(); // save changes
//Check in the Page
file.CheckIn("Created programmatically");
If you want to auto-approve and publish the page, then you could use the following in addition
file.Approve("Approved programmatically");
file.Publish("Published programmatically");
Code snippet :
using(PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web))
{
PageLayout myLayout = pWeb.GetAvailablePageLayouts()["Page Layout Name"];
PublishingPage newPage = pWeb.GetPublishingPages().Add("NewPage.aspx", myLayout);
newPage.Update(); // commit to the database
}
// apply the HTML properties
SPFile file = web.GetFile(newPage.Url);
SPListItem item = file.Item;
item["Title"] = "New Page Title";
item["Page Content"] = "
Some Text in the new page
";item.Update(); // save changes
//Check in the Page
file.CheckIn("Created programmatically");
If you want to auto-approve and publish the page, then you could use the following in addition
file.Approve("Approved programmatically");
file.Publish("Published programmatically");
you wrote:
ReplyDelete___
PageLayout myLayout = pWeb.GetAvailablePageLayouts()["Page Layout Name"];
___
GetAvailablePageLayouts returns array, and i can't access to item of it via Page Layout Name, but only by integer number.
Is it your mistake or mine?
where do you write this code to make it work? could you please explain in more detail ?
ReplyDeleteUse System.Linq and try:
ReplyDeletePageLayout myLayout = pWeb.GetAvailablePageLayouts.First(l => l.Title == "Page Layout Title");
Afterwards check myLayout == null.
Ups, use pWeb.GetAvailablePageLayouts.FirstOrDefault() or you'll not get null if not available ;-)
ReplyDelete