代码之家  ›  专栏  ›  技术社区  ›  Bob Kaufman

如何在ASP.NET窗体上设置必需的复选框?

  •  107
  • Bob Kaufman  · 技术社区  · 15 年前

    我已经对此做了一些调查,并且找到了几个部分的答案,但是没有什么能给我温暖的模糊的“这是正确的方法”。要回答针对此问题最常见的投诉:“复选框可以有两个合法状态-选中和未选中”,这是一个“我接受条款和条件…”复选框,必须选中该复选框才能完成注册,因此从业务逻辑的角度来看需要选中该复选框。

    请提供完整的剪切n粘贴准备代码片段与您的响应!我知道这其中有几个部分——自定义验证器(大概),代码隐藏,一些javascript,可能还有一个对isvalid的检查,而让我沮丧的是,在我看到的每个示例中,其中一个关键部分都丢失了!

    6 回复  |  直到 15 年前
        1
  •  210
  •   Chris    14 年前

    用于客户端验证的javascript函数(使用jquery)…

    function CheckBoxRequired_ClientValidate(sender, e)
    {
        e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');
    }
    

    服务器端验证的代码隐藏…

    protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = MyCheckBox.Checked;
    }
    

    复选框验证程序的ASP.NET代码…

    <asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
    <asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
        OnServerValidate="CheckBoxRequired_ServerValidate"
        ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>
    

    最后,在你的回邮中-无论是按钮还是其他什么…

    if (Page.IsValid)
    {
        // your code here...
    }
    
        2
  •  18
  •   John Rasch    15 年前

    安德鲁答案的C版:

    <asp:CustomValidator ID="CustomValidator1" runat="server" 
            ErrorMessage="Please accept the terms..." 
            onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
        <asp:CheckBox ID="CheckBox1" runat="server" />
    

    代码落后:

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = CheckBox1.Checked;
    }
    
        3
  •  12
  •   CirrusABS    13 年前

    如果您想要一个不依赖jquery并处理服务器端验证的真正的验证程序(您应该这样做)。服务器端验证是最重要的部分)然后这里是一个控件

    public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
    {
        private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
        protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
        {
            get
            {
                if (_ctrlToValidate == null)
                    _ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;
    
                return _ctrlToValidate;
            }
        }
    
        protected override bool ControlPropertiesValid()
        {
            if (this.ControlToValidate.Length == 0)
                throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));
    
            if (this.CheckBoxToValidate == null)
                throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));
    
            return true;
        }
    
        protected override bool EvaluateIsValid()
        {
            return CheckBoxToValidate.Checked;
        }
    
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
    
            if (this.Visible && this.Enabled)
            {
                System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
                if (this.DetermineRenderUplevel() && this.EnableClientScript)
                {
                    cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
                }
                if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
                {
                    cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
                } 
            }
        }
    
        private string GetClientSideScript()
        {
            return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
        }
    }
    
        4
  •  5
  •   jorelli    15 年前

    斯科特的答案适用于各种类型的复选框。如果你想要单独的复选框,你必须更狡猾一点。如果你只做一个盒子,最好用ID。这个例子通过特定的复选框实现,不需要jquery。这也是一个很好的例子,说明如何将这些讨厌的控件ID输入到JavaScript中。

    ASCX:

    <script type="text/javascript">
    
        function checkAgreement(source, args)
        {                
            var elem = document.getElementById('<%= chkAgree.ClientID %>');
            if (elem.checked)
            {
                args.IsValid = true;
            }
            else
            {        
                args.IsValid = false;
            }
        }
    
        function checkAge(source, args)
        {
            var elem = document.getElementById('<%= chkAge.ClientID %>');
            if (elem.checked)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }    
        }
    
    </script>
    
    <asp:CheckBox ID="chkAgree" runat="server" />
    <asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
    <asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
    <asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
    <br />
    
    <asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
        ClientValidationFunction="checkAgreement">
        You must agree to the terms and conditions.
        </asp:CustomValidator>
    
    <asp:CheckBox ID="chkAge" runat="server" />
    <asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
    <asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
        ClientValidationFunction="checkAge">
        You must be 18 years or older to continue.
        </asp:CustomValidator>
    

    以及背后的代码:

    Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
    Handles chkAgreeValidator.ServerValidate
        e.IsValid = chkAgree.Checked
    End Sub
    
    Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
    Handles chkAgeValidator.ServerValidate
        e.IsValid = chkAge.Checked
    End Sub
    
        5
  •  2
  •   Rob    10 年前

    我通常在客户端执行验证:

    <asp:checkbox id="chkTerms" text=" I agree to the terms" ValidationGroup="vg" runat="Server"  />
    <asp:CustomValidator id="vTerms"
                    ClientValidationFunction="validateTerms" 
                    ErrorMessage="<br/>Terms and Conditions are required." 
                    ForeColor="Red"
                    Display="Static"
                    EnableClientScript="true"
                    ValidationGroup="vg"
                    runat="server"/>
    
    <asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" CausesValidation="true" Text="Submit" ValidationGroup="vg" runat="server" />
    
    <script>
        function validateTerms(source, arguments) {
            var $c = $('#<%= chkTerms.ClientID %>');
            if($c.prop("checked")){
                arguments.IsValid = true;
            } else {
                arguments.IsValid = false;
            }
        }
    </script>       
    
        6
  •  -1
  •   andrewWinn    15 年前

    非javascript方式。. ASPX页:

     <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="CheckBox1" runat="server" />
        <asp:CustomValidator ID="CustomValidator1"
            runat="server" ErrorMessage="CustomValidator" ControlToValidate="CheckBox1"></asp:CustomValidator>
    </div>
    </form>
    

    代码落后:

    Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
        If Not CheckBox1.Checked Then
            args.IsValid = False
        End If
    End Sub
    

    对于您可能需要的任何操作(业务规则):

    If Page.IsValid Then
       'do logic
    End If 
    

    抱歉,我的代码是vb。..。如果您愿意的话,您可以把它转换成C。我现在工作的公司需要vb:。(