我在一个页面上有 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/