Treeview验证

3 javascript c# asp.net treeview webforms

树视图具有叶节点复选框.如果检查了至少一个节点并且不超过用户可以选择的特定节点(比如说3个节点),则需要验证树视图.注意:Treeview是一个asp.net树视图(不是ajax树视图)

Jul*_*lin 11

好吧,既然你没有提到你想要什么类型的验证,我会做客户端和服务器端.我TreeView的名字是tvTest
First,CustomValidator给你添加一个Asp.Net页面:

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ClientValidate"
  ErrorMessage="CustomValidator" Display="Dynamic" OnServerValidate="CustomValidator1_ServerValidate">*</asp:CustomValidator>
Run Code Online (Sandbox Code Playgroud)

注意:不要设置ControlToValidate属性.
接下来,添加此脚本(也是您的Asp.Net页面)以进行客户端验证:

<script type="text/javascript">

  function ClientValidate(source, arguments) {
    var treeView = document.getElementById("<%= tvTest.ClientID %>");
    var checkBoxes = treeView.getElementsByTagName("input");
    var checkedCount = 0;
    for (var i = 0; i < checkBoxes.length; i++) {
      if (checkBoxes[i].checked) {
        checkedCount++;
      }
    }
    if (checkedCount > 0 && checkedCount < 4) {
      arguments.IsValid = true;
    } else {
      arguments.IsValid = false;
    }
  }        

</script>
Run Code Online (Sandbox Code Playgroud)

最后,将此添加到服务器端验证的代码隐藏中:

protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args) {
  if (tvTest.CheckedNodes.Count > 0 && tvTest.CheckedNodes.Count < 4) {
    args.IsValid = true;
  } else {
    args.IsValid = false;
  }
}
Run Code Online (Sandbox Code Playgroud)

当然,您需要更改用户可以检查的最小和最大节点数的限制.