5

I want to do something like this:

I got this User Control called Base:

<div>
some content...

<asp:ContentPlaceHolder id="baseContentPlaceHolder" runat="server"></asp:ContentPlaceHolder>

</div>

Then i inherit the Base in another User Control and add stuff to the content:

<asp:Content id="subBase" contentplaceholderid="baseContentPlaceHolder" runat"server">
    stuff to be added...
</asp:Content>

Is it possible to do with ContentPlaceHolder ?

How can this behavior be solved?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
The Demz
  • 7,066
  • 5
  • 39
  • 43

2 Answers2

6

I don't think you can do that.

A ContentPlaceHolder can only go in the MasterPage itself.

In the pages that inherit from the MasterPage, you put in a Content tag.

My best guess would be to add in a PlaceHolder, expose that on the control, and then add in your stuff to that.

Jim B
  • 8,344
  • 10
  • 49
  • 77
  • 3
    Yep, You can't use a ContentPlaceHolder in a User Control, but just to clarify yes you can add the contents of regular PlaceHolder to the page from within a user control, or add/modify the contents of a regular PlaceHolder in a derived UserControl. example: http://stackoverflow.com/a/1973773/132461 – DanO Apr 04 '13 at 16:31
0

You can loop through the Master pages until you find the ContentPlaceHolder and insert it there:

var scriptTag = new HtmlGenericControl("script");
scriptTag.Attributes.Add("type", "text/javascript");
scriptTag.Attributes.Add("src", Page.ResolveUrl($"~/somescript.js"));

Control control = null;
MasterPage master = Page.Master;

while (master != null)
{
    control = master.FindControl("FooterContent");
    if (control == null)
        master = master.Master;
    else
        break;
}
control.Controls.Add(scriptTag);
codeMonkey
  • 4,134
  • 2
  • 31
  • 50