Sub items for server control
I've been trying to create a server control. I've been trying to get my MenuItem to contain other MenuItems under neath it like this
<cc1:DynamicMenu ID="DynamicMenu1" runat="server">
<MenuItems>
<cc1:MenuItem Text="" Url="">
<cc1:MenuItem Text="" Url="">
<cc1:MenuItem Text="" Url=""></cc1:MenuItem>
</cc1:MenuItem>
<cc1:MenuItem Text="" Url="">
<cc1:MenuItem Text="" Url=""></cc1:MenuItem>
</cc1:MenuItem>
</cc1:MenuItem>
</MenuItems>
</cc1:DynamicMenu>
but my code only gives me this
<cc1:DynamicMenu ID="DynamicMenu1" runat="server">
<MenuItems>
<cc1:MenuItem Text="" Url="">No other child elements for MenuItem</cc1:MenuItem>
</MenuItems>
</cc1:DynamicMenu>
I have played around with ParseChildren and PersistChildren swaping there values from true or false and I've run out of ideas could someone please help me with to resolve my problem below is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.Collections;
namespace Gravity.Controls
{
[AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[ParseChildren(true), PersistChildren(true)]
[ToolboxData("<{0}:DynamicMenu runat=\"server\"></{0}:DynamicMenu>")]
public class DynamicMenu : WebControl
{
public DynamicMenu()
{
}
List<MenuItem> _menuItems;
[PersistenceMode(PersistenceMode.InnerProperty)]
public List<MenuItem> MenuItems
{
get
{
if(_menuItems == null)
_menuItems = new List<MenuItem>();
return _menuItems;
}
}
}
[ParseChildren(false), PersistChildren(true)]
public class MenuItem: INamingContainer
{
private string _text;
private string _url;
public MenuItem(string text, string url)
{
}
public MenuItem()
: this("", "")
{
}
public str开发者_StackOverflowing Text
{
get
{
return _text;
}
set
{
_text = value;
}
}
public string Url
{
get
{
return _url;
}
set
{
_url = value;
}
}
private List<MenuItem> _subMenuItems;
public List<MenuItem> SubMenuItems
{
get
{
if (_subMenuItems == null)
_subMenuItems = new List<MenuItem>();
return _subMenuItems;
}
}
}
}
You need to dynamically add an instance of your custom control to itself in the OnItemDataBound event. This will re-curse until your business logic condition is met(ie:no children, so don't add another control) within the OnItemDataBound.
I think you should use these attribs:
[ParseChildren(true), PersistChildren(false)]
public class DynamicMenu
and
[ParseChildren(typeof(MenuItem), DefaultProperty = "SubMenuItems", ChildrenAsProperties = true)]
public class MenuItem
精彩评论