asp.net - 如何检查至少有一个 RadioButtonList 选中了一个项目?

标签 asp.net vb.net validation radiobuttonlist

我在一个页面上有 20 个 RadioButtonList

我需要创建一个验证方法以确保这些 RadioButtonList 中至少有一个选择了一个项目。

我需要为此使用什么样的验证?

最佳答案

编辑:根据评论和说明更新了问题。

如果您要针对多个 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 控件 ( Source ):

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。希望这能解决您的问题。

关于asp.net - 如何检查至少有一个 RadioButtonList 选中了一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5145574/

相关文章:

c# - 来自数据源的 String 类型的给定值无法转换为指定目标列的 float 类型

JavaScript "MULTIPLE Selection"选择框验证?

vb.net - 有没有办法在程序运行时创建 Onclick 事件?

.net - 列出 2 个日期时间中的可用时间

jquery - ASP.Net MVC 2 - jQuery 验证和表单提交 - DataAnnotations

php - 如何在 PHP 中选择 "remember"表单值?

javascript - 使用 [Authorize] 关键字是 ASP.NET MVC Controller 停止脚本代码运行

asp.net - IIS Express 在编辑 css、js 或其他 "no bin"文件后回收应用程序池

html - 页面拆分时如何停止打破表格边框?

.net - 在 VB.NET 中确定文件大小