我在页面上有20个RadioButtonList
。
我需要创建一个验证方法,确保至少有一个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
控件 (来源):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);
}
你可以为你的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>
编辑 如下方评论所指出的,这本身并不足以作为验证的手段。在服务器端进行验证所有用户输入是最佳实践。
我使用一个扩展方法,适用于ListControls
public static bool IsAnyItemSelected(this ListControl input) { return input.Items.Cast<ListItem>().Aggregate(false, (current, listItem) => current | listItem.Selected); }