如何使一个ASP.NET表单上需要一个复选框? [英] How do I make a checkbox required on an ASP.NET form?

查看:122
本文介绍了如何使一个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.

请提供完整切正准备贴code片段与您的回复!我知道有几件到这 - 的CustomValidator(presumably)时,code-的背后,一些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-落后于服务器端验证...

code-behind for server side validation...

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

ASP.Net code的复选框和放大器;验证...

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天全站免登陆