【问题标题】:item.Selected is false when the checkboxlist is disabled.当复选框列表被禁用时,item.Selected 为 false。
【发布时间】:2017-02-18 21:20:55
【问题描述】:

我有一个复选框列表,其中某些项目对某些用户禁用。

当我单击“保存”时,将执行以下代码。

 foreach (ListItem item in myCheckBoxList.Items)
 {
    if (!item.Selected)
            {
                continue;
            }
    selectedValues.Add(item.Value);
  }  

但是,对于禁用的项目,item.Selected 的计算结果为 false,即使它们已被选中。

有没有办法解决这个问题?

【问题讨论】:

  • 我认为这是因为禁用的复选框并没有真正通过 POST 发送到服务器。更多详情请见this answer

标签: c# asp.net


【解决方案1】:

禁用的输入永远不会发布到服务器,因此它将被设置为默认值,即 false。您可以使用HiddenField 并将其与每个复选框相关联,并根据其选择设置其值。

【讨论】:

  • 这是不正确的。你甚至测试过它吗?它们不会发布到服务器上,但这并不意味着 aspnet 不会将它们重新调整为已检查。
  • 什么???它们没有发布到服务器上,但这并不意味着 aspnet 不会将它们重新调整为已检查???如果某些内容甚至没有发布,那么如何将其识别为已检查??
  • @Imad 谢谢。我没有意识到他们没有被发布到服务器上。我现在有一个解决方案来解决它。谢谢。
【解决方案2】:

如果 CheckBoxList 的 ListItems 使用 aspnet 添加,无论是在代码后面还是在 .aspx 页面中,ViewState 都会确保将这些禁用的复选框视为已选中,即使它们没有发送到服务器。

    protected void Button1_Click(object sender, EventArgs e)
    {
        List<string> selectedValues = new List<string>();
        Label1.Text = "";
        foreach (ListItem item in myCheckBoxList.Items)
        {
            if (item.Selected)
            {
                selectedValues.Add(item.Value);
                Label1.Text += item.Value + "<br>";
            }
        }
    }

为了使示例完整:

    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <br /><br />
    <asp:CheckBoxList ID="myCheckBoxList" runat="server">
        <asp:ListItem Text="Blueberry" Value="Blueberry"></asp:ListItem>
        <asp:ListItem Text="Raspberry" Value="Raspberry"></asp:ListItem>
        <asp:ListItem Text="Blackberry" Value="Blackberry"></asp:ListItem>
        <asp:ListItem Text="Strawberry" Value="Strawberry" Enabled="false" Selected="True"></asp:ListItem>
        <asp:ListItem Text="Gooseberry" Value="Gooseberry" Enabled="false" Selected="True"></asp:ListItem>
    </asp:CheckBoxList>
    <br /><br />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

【讨论】:

  • 发帖前自己测试过。我可以向你保证确实如此。也许您的问题出在其他地方,例如在 ListItems 的投标中。
猜你喜欢
  • 2018-08-03
  • 2018-08-05
  • 1970-01-01
  • 2019-02-19
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-25
相关资源
最近更新 更多