ASP.NET User Control with Template Content

Asp.net user controls are great.  I use them all the time when working on .net websites.  I was working on a site using the asp.net ajax extender toolkit.  I created a panel that could be expanded collapsed with a button click.  I inserted a few into the site and liked them so much I made some more.  Well after the 7th panel it started getting tedious.  What a perfect place for a user control.  The problem was I needed to be able to place whatever custom content I wanted inside the panel.  After much searching around I wasn't finding what I wanted.  The answer it turns out is an asp.net user control with custom templates.

Create a new user control for your asp.net site.  Mine is called CollapsiblePanel.  In the code behind for the page you need to add a new class MessageContainer that inherits from Control and implements the INamingContainer Interface.   Then in the user controls OnInit method you need to check for content and add it to your user control.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test.UserControls
{
    // this is a message container, it contins the data we want to display
    // as well as the index of the container
    public class MessageContainer : Control, INamingContainer
    {
        private int index;
        internal MessageContainer(int index) { this.index = index; }
        public int Index { get { return index; } }
    }

   // this is the user control I have created
   //its an ajax extended collapsible panel with some custom content
    public partial class CollapsiblePanel : System.Web.UI.UserControl, INamingContainer
    {
        private ITemplate _contentTemplate = null;

        [TemplateContainer(typeof(MessageContainer))]
        public ITemplate Content
        {
            get { return _contentTemplate; }
            set { _contentTemplate = value; }
        }
     
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // if we have a content template in the markup then add it to our container
            if (_contentTemplate != null)
            {
                MessageContainer container = new MessageContainer(0);
                _contentTemplate.InstantiateIn(container);
                this.ContentHolder.Controls.Add(container);
            }
        }
    }
}

Now to use our new user control in an aspx page with some content.


<uc:CollapsiblePanel runat="server" ID="CollapsiblePanel1">
        <content>
          CONTENT GOES HERE,You can drop anything, asp.net controls, etc.            
        </content>
    </uc:CollapsiblePanel>

Comments

Popular Posts