Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何验证内容页中的复选框列表?_C#_Javascript_Asp.net_Validation_Checkbox - Fatal编程技术网

C# 如何验证内容页中的复选框列表?

C# 如何验证内容页中的复选框列表?,c#,javascript,asp.net,validation,checkbox,C#,Javascript,Asp.net,Validation,Checkbox,我在母版页的内容页中选择一个复选框列表,通过它我可以选择多个值并保存在数据库中。如何确认在单击“提交”按钮时选中了至少一个复选框。您可以执行以下操作 在JavaScript中,控件的位置、内容页或母版页都无关紧要 <asp:CheckBoxList ID="chkModuleList"runat="server" /> <asp:CustomValidator runat="server" ID="cvmodulelist" ClientValidationFunctio

我在母版页的内容页中选择一个复选框列表,通过它我可以选择多个值并保存在数据库中。如何确认在单击“提交”按钮时选中了至少一个复选框。

您可以执行以下操作

在JavaScript中,控件的位置、内容页或母版页都无关紧要

<asp:CheckBoxList ID="chkModuleList"runat="server" />

<asp:CustomValidator runat="server" ID="cvmodulelist"
  ClientValidationFunction="ValidateModuleList"
  ErrorMessage="Please Select Atleast one Module" />

// javascript to add to your aspx page
function ValidateModuleList(source, args)
{
  var chkListModules= document.getElementById ('<%= chkModuleList.ClientID %>');
  var chkListinputs = chkListModules.getElementsByTagName("input");
  for (var i=0;i<chkListinputs .length;i++)
  {
    if (chkListinputs [i].checked)
    {
      args.IsValid = true;
      return;
    }
  }
  args.IsValid = false;
}
您可能希望在这些复选框的容器上添加(或使用)一个id,以优化选择器速度。

对于asp.net在控件上弄乱客户端ID,您可以使用

$('<%= MyControl.ClientID %>')
$(“”)
参考资料:

    • ,GitHub上的一个库,也很好地处理了这个问题

      <asp:CheckBoxList ID="cblCheckBoxList" runat="server">
          <asp:ListItem Text="Check Box (empty)" Value="" />
          <asp:ListItem Text="Check Box 1" Value="1" />
          <asp:ListItem Text="Check Box 2" Value="2" />
          <asp:ListItem Text="Check Box 3" Value="3" />
      </asp:CheckBoxList>
      
      <Dado:RequiredFieldValidator runat="server" ControlToValidate="cblCheckBoxList" ValidationGroup="vlgSubmit" />
      

      是否要在java脚本中进行验证?
      <asp:CheckBoxList ID="cblCheckBoxList" runat="server">
          <asp:ListItem Text="Check Box (empty)" Value="" />
          <asp:ListItem Text="Check Box 1" Value="1" />
          <asp:ListItem Text="Check Box 2" Value="2" />
          <asp:ListItem Text="Check Box 3" Value="3" />
      </asp:CheckBoxList>
      
      <Dado:RequiredFieldValidator runat="server" ControlToValidate="cblCheckBoxList" ValidationGroup="vlgSubmit" />
      
      btnSubmit.Click += (a, b) =>
      {
          Page.Validate("vlgSubmit");
          if (Page.IsValid) {
              // Validation Successful
          }
      };