Add web part to sharepoint page in aspx markup

三世轮回 提交于 2019-12-05 07:04:09

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/557204/add-web-part-to-sharepoint-page-in-aspx-markup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!