Oct 30 2006

ASP.NET server control with multiple custom children collections

Posted by admin under Controls

I have been sitting for days trying to get my server control to support a tag construct such as:



<jquery:FooBarHolderControl ID="idHolder" runat="server">
<Bars>
<jquery:Bar Text="Pekka" />
<jquery:Bar Text="Another" />
</Bars>
<Foos>
<jquery:Foo Name="whatever" />
<jquery:Foo Name="a2" Position="A" />
</Foos>
</jquery:FooBarHolderControl>



I have been trying every single combination of ParseChildren, PersistChildren, PersistenceMode etc and since I have finally gotten it working - here's the code:



using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;

namespace JQueryASPNET
{
    [DefaultProperty("Name")]
    public class Foo
    {
        private string m_strName = "foo123";

        public string Name
        {
            get { return m_strName; }
            set { m_strName = value; }
        }
        private string m_strPosition = "Whatever";

        public string Position
        {
            get { return m_strPosition; }
            set { m_strPosition = value; }
        }
    }
        [DefaultProperty("Text")]
        public class Bar
        {
            private string m_strText = "Yellow";

            public string Text
            {
                get { return m_strText; }
                set { m_strText = value; }
            }
        }


    [ParseChildren(true)]
    [PersistChildren(false)]
        [ToolboxData("<{0}:FooBarHolderControl runat=server></{0}:FooBarHolderControl>")]
    public class FooBarHolderControl : Control
    {
        private List<Foo> pFoos = new List<Foo>();
        private List<Bar> pBars = new List<Bar>();

        [NotifyParentProperty(true)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<Foo> Foos
        {
            get { return pFoos; }
        }


        [NotifyParentProperty(true)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<Bar> Bars
        {
            get { return pBars; }
        }
    }

}