我在页面上有20个RadioButtonList
。
我需要创建一个验证方法,以确保这些RadioButtonList
中至少有一个选择了一个项目。
我需要使用哪种验证?
答案 0 :(得分: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
控件(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。希望这能解决你的问题。
答案 1 :(得分: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>
修改强> 的 正如下面的评论中指出的那样,这本身并不足以作为一种验证手段。优良作法是验证服务器端的所有用户输入。
答案 2 :(得分:0)
我使用适用于ListControls的扩展方法
public static bool IsAnyItemSelected(this ListControl input) { return input.Items.Cast<ListItem>().Aggregate(false, (current, listItem) => current | listItem.Selected); }