ademers
ademers

Reputation: 967

ASP.NET User Control inner content

I have a user control which accepts a title attribute. I would also like that input inner HTML (ASP Controls also) inside of that user control tag like so:

<uc:customPanel title="My panel">
     <h1>Here we can add whatever HTML or ASP controls we would like.</h1>
     <asp:TextBox></asp:TextBox>
</uc:customPanel>

How can I achieve this? I have the title attribute working correctly.

Thanks.

Upvotes: 4

Views: 5229

Answers (2)

toxaq
toxaq

Reputation: 6838

You need to make sure EnsureChildControls is called. There are number of ways of doing that such as through the CreateChildControls base method but you can simply do this to get the inner contents of a custom control to render. It gets more complicated when you need to remember state and trigger events but for plain HTML this should work.

protected override void Render(HtmlTextWriter writer) {
    EnsureChildControls();
    base.Render(writer);
}

Upvotes: 0

joerage
joerage

Reputation: 4923

Implement a class that extends Panel and implements INamingContainer:

public class Container: Panel, INamingContainer
{
}

Then, your CustomPanel needs to expose a property of type Container and another property of type ITemplate:

public Container ContainerContent
{
    get
    {
       EnsureChildControls();
       return content;
    }
}
[TemplateContainer(typeof(Container))]
[TemplateInstance(TemplateInstance.Single)]
public virtual ITemplate Content
{
    get { return templateContent; }
    set { templateContent = value; }
}

Then in method CreateChildControls(), add this:

if (templateContent != null)
{
    templateContent.InstantiateIn(content);
}

And you will be using it like this:

<uc:customPanel title="My panel"> 
    <Content>    
        <h1>Here we can add whatever HTML or ASP controls we would like.</h1>
        <asp:TextBox></asp:TextBox>
     </Content>
</uc:customPanel>

Upvotes: 7

Related Questions