<asp:RadioButton ID="RadioButton1" runat="server" Text="A" GroupName="rbn" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="B" GroupName="rbn" />
<asp:RadioButton ID="RadioButton3" runat="server" Text="C" GroupName="rbn"/>
<asp:RadioButton ID="RadioButton4" runat="server" Text="D" GroupName="rbn"/>
<asp:Button ID="Button1" runat="server" Text="Validate" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
点击按钮Validate
它应该验证单选按钮组rbn
并在Label1
中显示已检查的单选按钮文本。
这应该在C#中完成。请不要使用任何脚本和for循环。
帮我解决这个问题并提前致谢
答案 0 :(得分:1)
您可以使用RadioButtonList
代替RadioButton
。要验证RadioButtonList
,请使用内置验证控件RequiredFieldValidator
来验证整个列表。
.aspx
<asp:RadioButtonList ID="RadioButtonList1" RepeatColumns="2"
RepeatDirection="Vertical" RepeatLayout="Table" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
<asp:ListItem>D</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1"
ControlToValidate="RadioButtonList1" Text="Required">
</asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Validate" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
.aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "You selected: ";
Label1.Text += RadioButtonList1.SelectedItem.Text.ToString();
}
注意:RequiredFieldValidator
必须位于RadioButtonList
(而不是每个ListItem)。
<强>更新强>
当您需要RadioButtons
代替RadioButtonList
时,请尝试以下操作:
HTML
<input type="radio" value="A" name="radiodbtn" runat="server" /> A
<input type="radio" value="B" name="radiodbtn" runat="server" /> B
<input type="radio" value="C" name="radiodbtn" runat="server" /> C
<input type="radio" value="D" name="radiodbtn" runat="server" /> D
<asp:CustomValidator runat="server" ID="validateCheckBoxes" EnableClientScript="true"
OnServerValidate="validateCheckBoxes_ServerValidate"
OnClientValidate="validateCheckBoxes_ClientValidate">Required</asp:CustomValidator>
然后为客户端验证添加Javascript:
<script type="text/javascript">
function CheckBoxRequired_ClientValidate(sender, e)
{
e.IsValid = $("input[name='radiodbtn']").is(':checked');
}
</script>
现在添加服务器端验证:
protected void validateCheckBoxes_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = RadioButton1.Checked || RadioButton2.Checked || RadioButton3.Checked || RadioButton4.Checked;
if(e.IsValid)
{
// at least any one radio button is checked among all group
}
else
{
// no radio button is checked among all group
}
答案 1 :(得分:1)
您可以使用RadioButtonList而不是Radiobutton Group。这是示例代码
<asp:RadioButtonList ID="rbList" runat="server">
<asp:ListItem Text="Option1" Value="A" Selected="True"></asp:ListItem> // Selected attribute is used to select a default value
<asp:ListItem Text="Option2" Value="B"></asp:ListItem>
</asp:RadioButtonList>
代码背后的
protected void btnGetValue_Click(object sender, EventArgs e)
{
string OptionName = rbList.SelectedValue;
}
您将所选的选项值输入OptionName变量