asp.netcustom-controlscontenttemplate

ASP.net Custom Control with Content Template didn't work for me


With regards to the solution at: ASP.Net: User control with content area, it's clearly possible but I need some details

I am trying to do the same and here is my code:

The control code behind:

[ParseChildren(true, "Content")]
[PersistChildren(false)]
public partial class SlidingPanelControl : System.Web.UI.UserControl
{
    protected override void OnInit(EventArgs e)
    {
        phContent.Controls.Add((Control)_content);
        base.OnInit(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    private PlaceHolder _content;
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public PlaceHolder Content { get { return _content; } set { _content = value; } }
}

And the control ASPX:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SlidingPanelControl.ascx.cs" Inherits="Photography.Controls.MbExtruder.SlidingPanelControl" %>
<div>
<asp:Panel ID="pnlLockable" runat="server" Visible="False">
    <asp:PlaceHolder runat="server" ID="phContent" />
</asp:Panel>
</div>

And this is how I am using the control in my main page:

<uc1:SlidingPanelControl runat="server" ID="SlidingPanelControl"
    Title="About" Position="right" Opacity="1" WidthInPixels="600">
    <Content><h1>hello world</h1></Content>
</uc1:SlidingPanelControl>

This didn't work for me, it didn't render the html into the control placeholder. Although when I debug OnInit of the control, I can see the _content control having all the html I set (i.e. <h1>Hello World</h1> in this example)

Any guesses what I am doing wrong?

Thanks


Solution

  • Ok, so i checked it on my computer and i found solution that actually works:

    [ParseChildren(false)]
    [PersistChildren(false)]
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (Content != null)
            {
                ContentContainer container = new ContentContainer();
                Content.InstantiateIn(container);
                phContent.Controls.Add(container);
            }
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        private ITemplate _content;
        [PersistenceMode(PersistenceMode.InnerDefaultProperty),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        TemplateInstance(TemplateInstance.Single)]
        public ITemplate Content
        {
            get
            {
                return _content;
            }
            set
            {
                _content = value;
            }
        }
    }
    
    public class ContentContainer : Control, INamingContainer
    {
    }
    

    I checked it myself works like a charm. Code in other sources is the same as yours.