How to define a Content Control through C# code
I am writing a webpart and was trying to update th开发者_StackOverflowe browser title... so, I went into mywebpart.ascx added the following:
<asp:Content ID="contentPageTitle" ContentPlaceholderID="PlaceHolderPageTitle" runat="server">
<%= SPContext.Current.Site.OpenWeb().Title %>
</asp:Content>
I then got this error: Content controls have to be top-level controls in a content page or a nested master page that references a master page.
So, I am trying to do it programatically in mywebpart.cs by doing:
Content content = new Content();
content.ContentPlaceHolderID = "PlaceHolderPageTitle";
I now need to input this piece: SPContext.Current.Site.OpenWeb().Title
What property in the Content control allows me to do that? If there is a better way to do this, I am open as well. Thanks.
Unfortunately, you cannot place a content control within a user control. As the error message indicates, content controls must be top level controls in a page or master page, and cannot belong in any other kind of control.
An alternate approach might be to customize your page layout or master page to contain the logic you want to provide.
If you have some assurance of the ID of the content control (not the ContentPlaceholderID, mind you), then you can interact with the content control like so:
var content = Page.FindControl("contentPageTitle");
content.Controls.Add(new LiteralControl("Hello, World!"));
--
On an aside, do ensure that any SPWeb opened with OpenWeb()
gets disposed properly, or you may face memory management problems down the road.
精彩评论