Asp.net custom control rendering outside of form tag

asp.netcustom-server-controls

I am having an issue with a custom control rendering its contents (child controls) outside of the tag which leads to runtime errors and issues. In an attempt to simplify things as much as I can, I created the control below but it has the very same issue. I have tried inheriting from Control, WebControl and CompositeControl all resulting in with the same problem. Guessing there is something obvious that I am doing wrong… Thanks for any help.

using System;
using System.Web.UI.WebControls;

namespace MyControls
{
    public class TestControl : CompositeControl
    {
        protected override void CreateChildControls()
        {
            Controls.Clear();
            Controls.Add(new Button() { Text = "TestControl!" });
            ClearChildViewState();
        }
    }
}

Adding the control programmatically results in markup outside the forms tag. Adding the control via markup works correct.

protected void Page_Load(object sender, EventArgs e)
{
    Controls.Add(new TestControl());
}



...
<body>
    <form name="PageForm" method="post" action="default.aspx" id="PageForm">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTE5MDEwMTE5MWRkg0FopdvLhTPGxHkGm1xCCOVQz6A=" />
</div>

    <div>

    </div>
    </form>
</body>
</html>
<span><input type="submit" name="ctl04$ctl00" value="TestControl!" /></span>

Best Answer

Adding the control through the Page.Form property will render the button inside the form.

Page.Form.Controls.Add(new Button() { Text = "TestControl!" });

However, since the button is not contained within a block, such as a <div>, you might have some layout issues with this button. Use ScarletGarden's approach.

Related Topic