views:

3436

answers:

2

I have an aspx page that get copied in the layouts directory of a Project Server instalation. The aspx is a web part page that has a web part zone. How can I add a web part in the markup of the page, within the web part zone?

+2  A: 

You can use the SPLimitedWebPart manager to add an instance of a web part at runtime. I do this on our MySites to control adding, deleting and moving web parts that the organization requires. You can put the code in the aspx page.

SPFile thePage = currentWeb.RootFolder.Files["default.aspx"]
using (Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager spLimitedWPManager = thePage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
       Assembly assembly = Assembly.Load("WebPartAssemblyName");
       WebPart webPart = (WebPart)assembly.CreateInstance("WebPartClassName");

       spLimitedWPManager.AddWebPart(webPart, ZoneId, ZoneIndex);
}

You may need to do something different to gain access to the Web Part Manager for your layouts page. After this you need to redirect back to the page to display the changes. You'll also want to store a bit value to ensure that you do not perform the action on each subsequent visit.

If you only need to do this once then I might recommend PowerShell instead.

Otherwise you can add the web part directly in MarkUp by registering the tag:

<%@ Register TagPrefix="ABC" Namespace="Namespace" Assembly="Assembly" %>

and directly adding the web part,

<ABC:ClassName ID="ControlID" FrameType="None" runat="server" __WebPartId="YouWebPartGUID" WebPart="true" />

but we didn't do it inside of a web zone because we did not want to allow it to be removed so I do not know if it works in that scenario. This is easiest but doesn't allow for any customization and SharePoint doesn't really "know" about the web part.

webwires
+3  A: 

You cannot have customizable Web Part pages in the layouts directory! This is only supported on Web Part pages stored in a document library or other folder in an SPWeb, i.e. ASPX files that you can get an SPFile reference to. Web Parts on ASPX pages in the layouts directory must be added as Web controls in the ASPX source.

Lars Fastrup
I see, however it seems the ProjectCenter page (http://ps/pwa/projects.aspx - for my install) is a web part page in the layouts directory. Is there a way around the restriction you have mentioned to create a similar web part page?
iulianchira
Well, if the URL does not contain _layouts then the file is not in the layouts folder. To me it more looks like the projects.aspx is located in the root folder of the Web site, i.e. SPWeb.RootFolder
Lars Fastrup