您可以使用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
(而不是每個列表項)。
UPDATE:
,因爲你需要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不表明你已經嘗試過,資本化每個單詞的第一個字母。 –
@DeeMac先生這是我第一次嘗試 – Selva