Add web part to sharepoint page in aspx markup

2019-04-02 14:30发布

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条回答
Anthone
2楼-- · 2019-04-02 15:09

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.

查看更多
时光不老,我们不散
3楼-- · 2019-04-02 15:15

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.

查看更多
登录 后发表回答