Add children controls within a ServerControl tags?
I'm working on a Navigation Menu.
I've created below ServerControl and it works, but I want to allow users adding some standard ASP.NET contro开发者_如何学Cls within my ServerControl Tags likelabel
, image
and so on.
<MdsMenu:ServerControlMenu ID="ServerControlMenu1" runat="server">
<MdsMenu:animation AnimationSpeed="Normal" AnimationType="Opacity_Height" Delay="1000" DropShadow="true" />
<!-- HERE HAS TO HAVE SOME STANDARD ASP.NET CONTROLS -->
<!-- e.g <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> -->
</MdsMenu:MenuItem>
</MdsMenu:ServerControlMenu>
My problem is here that how I can get Child Controls within <MdsMenu:MenuItem>
and show them like as they are in the output.
P.S:
I overwriteRenderContents
method
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(OutPutStringBuilder.ToString());
}
I think you will just have to throw [ParseChildren(false), PersistChildren(true)]
on the class that represents the <MdsMenu:MenuItem/>
tag. Child controls written inside the tag should then be available at runtime in the control's Controls
property.
UPDATE: I threw together a quick test project to demonstrate that this actually works. (Apparently people like to downvote without actually evaluating whether an answer is correct.)
This custom control has the behavior you would expect:
[ParseChildren(false), PersistChildren(true)]
public partial class SuperDiv : System.Web.UI.UserControl
{
public override void RenderControl(HtmlTextWriter writer)
{
writer.Write("<div class=\"super\">");
writer.Write(Controls.Count);
foreach (Control i in Controls)
i.RenderControl(writer);
writer.Write("</div>");
}
}
So the following ASP.NET markup:
<test:SuperDiv runat="server">
<asp:Label runat="server">Hello, World!</asp:Label>
</test:SuperDiv>
Will result in the following HTML being rendered:
<div class="super">3
<span>Hello, World!</span>
</div>
(3 because the two text nodes containing only whitespace are also children of the control, as well as the label.)
you need to make your web control act as a container (like the panel control)
just add the attributes showed below to your web user control class
[ParseChildren(false)]
[PersistChildren(true)]
[Designer(typeof(PanelDesigner))]
public class MyOwnControl:WebControl
{
}
then on the .aspx page you will be able to do the below:
<cc1:MyOwnControl ID="MyOwnControl1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</cc1:MyOwnControl>
精彩评论