如何在ASP.NET表单上创建一个复选框?

Bob*_*man 109 asp.net validation checkbox

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

请提供完整的cut-n-paste ready代码片段与您的回复!我知道有几个部分 - CustomValidator(大概),代码隐藏,一些javascript和可能的IsValid检查,对我来说令人沮丧的部分是在我看过的每个例子中,其中一个是关键的件丢失了!

Sco*_*vey 213

用于客户端验证的javascript函数(使用jQuery)...

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

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

protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
{
    e.IsValid = MyCheckBox.Checked;
}
Run Code Online (Sandbox Code Playgroud)

复选框和验证器的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>
Run Code Online (Sandbox Code Playgroud)

最后,在你的回发 - 无论是从按钮还是其他...

if (Page.IsValid)
{
    // your code here...
}
Run Code Online (Sandbox Code Playgroud)

  • 完整正确的答案,包括代码; p. (8认同)
  • 啊,对.只需删除它 - CheckBox没有实现正确的接口来绑定它.如果没有设置该属性,验证器仍然可以正常运行.我会相应地更新我的例子. (2认同)
  • javascript函数名称的CustomValidator参数应为"ClientValidationFunction",而不是"OnClientValidate".请参阅:http://msdn.microsoft.com/en-us/library/9eee01cx(v = VS.100).aspx (2认同)
  • 我最初没有注意到没有ControlToValidate属性.包含此属性会导致异常,因此向其他人发出警告,也可能会错过. (2认同)

Joh*_*sch 18

C#版安德鲁的回答:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
        ErrorMessage="Please accept the terms..." 
        onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    <asp:CheckBox ID="CheckBox1" runat="server" />
Run Code Online (Sandbox Code Playgroud)

代码隐藏:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = CheckBox1.Checked;
}
Run Code Online (Sandbox Code Playgroud)


小智 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>";
    }
}
Run Code Online (Sandbox Code Playgroud)


jor*_*lli 5

斯科特的答案将适用于复选框类.如果你想要个人复选框,你必须有点偷偷摸摸.如果你只是做一个盒子,最好用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>
Run Code Online (Sandbox Code Playgroud)

而代码隐藏:

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
Run Code Online (Sandbox Code Playgroud)


Rob*_*Rob 5

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

<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>       
Run Code Online (Sandbox Code Playgroud)