Search code examples
c#asp.netwebformspostback

Why are InputAttributes and LabelAttributes of a CheckBox not rendered after a postback?


I’m seeing some weird behavior in the standard ASP.NET CheckBox control. Here’s a repro:

ASPX markup

<form runat="server">
    <asp:CheckBox runat="server" ID="cb" Text="Foo" />
    <asp:Button runat="server" Text="Submit" />
</form>

C# code-behind

protected override void OnLoad(EventArgs e)
{
    if (!IsPostBack)
    {
        cb.Attributes.Add("data-a", "1");
        cb.InputAttributes.Add("data-b", "2");
        cb.LabelAttributes.Add("data-c", "3");
    }
}

On the initial page request, the CheckBox control renders all three data attributes:

<span data-a="1">                                           <!-- RIGHT -->
    <input id="cb" type="checkbox" name="cb" data-b="2" />  <!-- RIGHT -->
    <label for="cb" data-c="3">Foo</label>                  <!-- RIGHT -->
</span>

But after I click the Submit button, the CheckBox control renders only the data-a attribute:

<span data-a="1">                                           <!-- RIGHT -->
    <input id="cb" type="checkbox" name="cb" />             <!-- WRONG -->
    <label for="cb">Foo</label>                             <!-- WRONG -->
</span>

Why are the InputAttributes and LabelAttributes missing after a postback?

Heisenbug Alert: If I set a breakpoint in OnLoad, click the button, and then inspect the values of cb.Attributes["data-a"], cb.InputAttributes["data-b"], and cb.LabelAttributes["data-c"], then the values are 1, 2, and null (instead of 3) respectively. Also, inspecting the values affects the output!

<span data-a="1">                                           <!-- RIGHT -->
    <input id="cb" type="checkbox" name="cb" data-b="2" />  <!-- RIGHT -->
    <label for="cb" data-b="2">Foo</label>                  <!-- WTF?! -->
</span>

Solution

  • In case you were still stuck on this, it's a bug.

    Upgrade to .net framework 4.8 (and greater) for a fix.

    I see you also submitted the bug report to Microsoft: https://developercommunity.visualstudio.com/content/problem/287564/buggy-handling-of-inputattributes-and-labelattribu.html