【问题标题】:Why are InputAttributes and LabelAttributes of a CheckBox not rendered after a postback?为什么回发后 CheckBox 的 InputAttributes 和 LabelAttributes 不呈现?
【发布时间】:2018-12-10 18:53:39
【问题描述】:

我在标准 ASP.NET CheckBox 控件中看到了一些奇怪的行为。这是一个再现:

ASPX 标记

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

C# 代码隐藏

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");
    }
}

在初始页面请求中,CheckBox 控件呈现所有三个data 属性:

<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>

但是在我点击提交按钮后,CheckBox 控件只呈现data-a 属性:

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

为什么回发后 InputAttributes 和 LabelAttributes 不见了?

Heisenbug Alert: 如果我在 OnLoad 中设置断点,单击按钮,然后检查 cb.Attributes["data-a"]cb.InputAttributes["data-b"]cb.LabelAttributes["data-c"] 的值,则值为 @987654330 @、2null(而不是 3)分别。此外,检查值会影响输出!

<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>

【问题讨论】:

    标签: c# asp.net webforms postback


    【解决方案1】:

    如果你仍然坚持这一点,这是一个错误。

    升级到 .net framework 4.8(及更高版本)进行修复。

    我看到你也向微软提交了错误报告:https://developercommunity.visualstudio.com/content/problem/287564/buggy-handling-of-inputattributes-and-labelattribu.html

    【讨论】:

    • 我打算发布一个包含一些细节的答案,但我一直没有时间去做。现在你打败了我。 :-)
    • 感谢您在开发者社区提出这个问题!很明显,您在错误报告和这个问题上付出了很多努力
    猜你喜欢
    • 2010-11-03
    • 2011-09-30
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    相关资源
    最近更新 更多