Tuesday, April 30, 2013

Create a Web Part Page Programmatically

When creating SharePoint Solutions we need to deploy Web part pages with the solution. I'm sure most of us deploy pages as a module. But we are copying aspx page from some ware else and include it to module. (Visual studio does not allow to create web part aspx pages in SharePoint Solutions) 

So I think it is good to use a method to create web part pages rather than copying from somewhere else and put it to the solution. Using below method you can add web part page to document library with  specified template. of cause you can add custom template ; in that case you can deploy custom template first and use the following method to create a web part page.

First you need to generate the XML for add Web Part Page

private string GetCreateWebPartPage(String list, string pageTitle, int layoutTemplate)
{
const string newItemTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Batch>" +
"<Method ID=\"0,NewWebPage\">" +
"<SetList Scope=\"Request\">{0}</SetList>" +
"<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +
"<SetVar Name=\"ID\">New</SetVar>" +
"<SetVar Name=\"Type\">WebPartPage</SetVar>" +
"<SetVar Name=\"WebPartPageTemplate\">{2}</SetVar>" +
"<SetVar Name=\"Overwrite\">true</SetVar>" +
"<SetVar Name=\"Title\">{1}</SetVar>" +
"</Method>" +
"</Batch>";
var newItemXml = string.Format(newItemTemplate, list, pageTitle, layoutTemplate);

return newItemXml;
}


Then Pass it to ProcessBatchData method in SPWeb to create the page.


using (SPWeb oWebsite = SPContext.Current.Site.OpenWeb("Website_URL"))
{
string xml = GetCreateWebPartPage("SitePages", "SamplePage", 2);
oWebsite.ProcessBatchData();
}



You can put the code in Feature Activation for deployment.

Post a Comment