如何检查至少有一个RadioButtonList被选中了?

3

我在页面上有20个RadioButtonList

我需要创建一个验证方法,确保至少有一个RadioButtonList被选中了其中的一项。

为此,我需要使用什么类型的验证?

3个回答

2

编辑: 基于评论和澄清更新问题.

如果您正在验证多个 RadioButtonList,那么您需要使用一个CustomValidator并实现服务器端检查.

这里是一些测试标记:

<asp:RadioButtonList ID="rblstTest1" runat="server" ValidationGroup="Test">
    <asp:ListItem Text="Test 1" Value="1" />
    <asp:ListItem Text="Test 2" Value="2" />
    <asp:ListItem Text="Test 3" Value="3" />
</asp:RadioButtonList>
<br /><br />
<asp:RadioButtonList ID="rblstTest2" runat="server" ValidationGroup="Test">
    <asp:ListItem Text="Test 1" Value="1" />
    <asp:ListItem Text="Test 2" Value="2" />
    <asp:ListItem Text="Test 3" Value="3" />
</asp:RadioButtonList><br />
<asp:Button ID="btnTestRb" runat="server" ValidationGroup="Test" Text="Test RBL" 
    OnClick="btnTestRb_Click" />
<asp:CustomValidator runat="server" ValidationGroup="Test" ID="cvTest" 
    ControlToValidate="rblstTest1" OnServerValidate="cvTest_ServerValidate" 
    ValidateEmptyText="true" Enabled="true" display="Dynamic" SetFocusOnError="true"
    ErrorMessage="You must select at least one item." /> 

使用以下扩展方法查找所有的 RadioButtonList 控件 (来源):
static class ControlExtension
{
    public static IEnumerable<Control> GetAllControls(this Control parent)
    {
        foreach (Control control in parent.Controls)
        {
            yield return control;
            foreach (Control descendant in control.GetAllControls())
            {
                yield return descendant;
            }
        }
    }
} 

然后实现服务器端的CustomValidator检查:

protected void cvTest_ServerValidate(object sender, ServerValidateEventArgs e)
{            
    int count = this.GetAllControls().OfType<RadioButtonList>().
        Where(lst => lst.SelectedItem != null).Count();
    e.IsValid = (count > 0);
 }

我已测试上述示例,它似乎正好符合您的需求。您应该可以很容易地将其转换为VB。希望这能解决您的问题。

只是为了澄清,我有20个不同的RadioButtonLists。没有一个是必填字段,但在提交表单之前,我需要至少填写其中一个。 - Tom

0

你可以为你的RadioButtonList设置一个默认值,这意味着用户永远不会没有选择选项,而且你也不需要所有的验证代码。

<asp:RadioButtonList ID="RadioButtonList1" runat="server">
    <asp:ListItem Selected="True">Never</asp:ListItem>
    <asp:ListItem>Twice A Week</asp:ListItem>
    <asp:ListItem>Every Day Baby!</asp:ListItem>
</asp:RadioButtonList>

编辑 如下方评论所指出的,这本身并不足以作为验证的手段。在服务器端进行验证所有用户输入是最佳实践。


这仍然允许在没有单选按钮选项的情况下创建HTTP请求。但需要伴随的服务器端代码来强制执行它。 - Joel Coehoorn

0

我使用一个扩展方法,适用于ListControls

        public static bool IsAnyItemSelected(this ListControl input) { return input.Items.Cast<ListItem>().Aggregate(false, (current, listItem) => current | listItem.Selected); }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接