如何在 ASP.NET 表单上创建所需的复选框? [英] How do I make a checkbox required on an ASP.NET form?

查看:16
本文介绍了如何在 ASP.NET 表单上创建所需的复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've done some searching on this, and I've found several partial answers, however nothing that gives me that warm fuzzy "this is the right way to do this". To answer the most frequently occurring complaint against this question: "checkboxes can have two legitimate states - checked and unchecked", this is an "I accept the terms and conditions..." checkbox which must be checked in order to complete a registration, hence checking the box is required from a business logic standpoint.

请在您的回复中提供完整的可剪切粘贴的代码片段!我知道这有几个部分——CustomValidator(大概)、代码隐藏、一些 javascript 和可能对 IsValid 的检查,对我来说令人沮丧的部分是,在我看到的每个例子中,这些关键之一件不见了!

Please provide complete cut-n-paste ready code fragments with your response! I know there are several pieces to this -- the CustomValidator (presumably), the code-behind, some javascript and possibly a check for IsValid, and the frustrating part for me is that in each example I've seen, one of these critical pieces is missing!

推荐答案

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

javascript function for client side validation (using jQuery)...

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

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

code-behind for server side validation...

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

复选框的 ASP.Net 代码 &验证器...

ASP.Net code for the checkbox & validator...

<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>

最后,在您的回发中 - 无论是通过按钮还是其他方式...

and finally, in your postback - whether from a button or whatever...

if (Page.IsValid)
{
    // your code here...
}

这篇关于如何在 ASP.NET 表单上创建所需的复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆