在ASP.NET自定义控件中呈现多个控件集合

Her*_*des 9 c# asp.net rendering custom-controls controlcollection

我构建了一个自定义WebControl,它具有以下结构:

<gws:ModalBox ID="ModalBox1" HeaderText="Title" runat="server">
    <Contents>
        <asp:Label ID="KeywordLabel" AssociatedControlID="KeywordTextBox" runat="server">Keyword: </asp:Label><br />
        <asp:TextBox ID="KeywordTextBox" Text="" runat="server" />
    </Contents>
    <Footer>(controls...)</Footer>
</gws:ModalBox>
Run Code Online (Sandbox Code Playgroud)

该控件包含两个ControlCollection属性,'Contents'和'Footer'.从未尝试使用多个控件集合构建控件,但是像这样(简化)解决了它:

[PersistChildren(false), ParseChildren(true)]
public class ModalBox : WebControl
{
    private ControlCollection _contents;
    private ControlCollection _footer;

    public ModalBox()
        : base()
    {
        this._contents = base.CreateControlCollection();
        this._footer = base.CreateControlCollection();
    }

    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ControlCollection Contents { get { return this._contents; } }

    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ControlCollection Footer { get { return this._footer; } }

    protected override void RenderContents(HtmlTextWriter output)
    {
        // Render content controls.
        foreach (Control control in this.Contents)
        {
            control.RenderControl(output);
        }

        // Render footer controls.
        foreach (Control control in this.Footer)
        {
            control.RenderControl(output);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是它似乎正确呈现,如果我在属性中添加一些asp.net标签和输入控件,它就不再起作用了(参见上面的asp.net代码).我会得到HttpException:

无法找到与标识'KeywordLabel'关联的id'KeywordTextBox'的控件.

有点可以理解,因为标签出现在controlcollection中的文本框之前.但是,使用默认的asp.net控件确实可行,所以为什么这不起作用呢?我究竟做错了什么?甚至可以在一个控件中有两个控件集合吗?我应该以不同的方式呈现它

谢谢你的回复.

Kae*_*ber 2

您可以使用两个面板作为两个控件集合的父级(它们将提供分组并提高可读性)。将每个集合中的控件添加到相应面板的 Controls 集合中,并在 Render 方法中调用每个面板的 Render 方法。面板会自动渲染它们的子面板,并为它们提供自己的命名空间,因此,您可以在不同的面板中拥有具有相似 ID 的控件。