Jquery 在MVC3中,如何要求在表单提交到服务器之前在客户端选中复选框?

Jquery 在MVC3中,如何要求在表单提交到服务器之前在客户端选中复选框?,jquery,asp.net-mvc-3,validation,Jquery,Asp.net Mvc 3,Validation,我在注册页面上有一个条款和条件复选框。 我想在发布到服务器之前,像表单上的其他几个字段一样将其设置为必填字段。 此验证必须在客户端完成 有人知道如何正确地做吗 我使用的是MVC 3、jquery.validate.min.js和jquery.validate.unobtrusive.min.js 型号: [Required(ErrorMessage = "terms and condition")] [Display(Name = "terms")] public bool Terms { ge

我在注册页面上有一个条款和条件复选框。 我想在发布到服务器之前,像表单上的其他几个字段一样将其设置为必填字段。 此验证必须在客户端完成

有人知道如何正确地做吗

我使用的是MVC 3、jquery.validate.min.js和jquery.validate.unobtrusive.min.js

型号:

[Required(ErrorMessage = "terms and condition")]
[Display(Name = "terms")]
public bool Terms { get; set; }
视图:

@Html.CheckBoxFor(m=>m.Terms,新的{@class=“cb”})术语和条件
报名
而且, 单击submit按钮时是否可以调用/捕获某些JS函数? 这样我就可以轻松地使用jquery进行验证,然后提交


感谢阅读

您可以编写自定义验证属性:

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value is bool && (bool)value)
        {
            return ValidationResult.Success;
        }
        return new ValidationResult(String.Format(ErrorMessageString, validationContext.DisplayName));
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "shouldbetrue"
        };

        yield return rule;
    }
}
最后在视图中注册它:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.CheckBoxFor(m => m.Terms, new { @class = "cb" }) 
    <text>Terms &amp; Condition</text>
    @Html.ValidationMessageFor(x => x.Terms)

    <button type="submit" id="btnSubmit" class="btn">Signup</button>
}

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>           
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>           

<script type="text/javascript">
    jQuery.validator.addMethod('shouldbetruemethod', function (value, element) {
        return $(element).is(':checked');
    }, '');

    jQuery.validator.unobtrusive.adapters.addBool('shouldbetrue', 'shouldbetruemethod');
</script>
@model MyViewModel
@使用(Html.BeginForm())
{
@CheckBoxFor(m=>m.Terms,新的{@class=“cb”})
条款及条件
@Html.ValidationMessageFor(x=>x.Terms)
报名
}
jQuery.validator.addMethod('shouldbetruemethod',函数(值,元素){
返回$(元素).is(':checked');
}, '');
jQuery.validator.unobtrusive.adapters.addBool('shouldbetrue','shouldbetruethod');

您可以编写自定义验证属性:

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value is bool && (bool)value)
        {
            return ValidationResult.Success;
        }
        return new ValidationResult(String.Format(ErrorMessageString, validationContext.DisplayName));
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "shouldbetrue"
        };

        yield return rule;
    }
}
最后在视图中注册它:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.CheckBoxFor(m => m.Terms, new { @class = "cb" }) 
    <text>Terms &amp; Condition</text>
    @Html.ValidationMessageFor(x => x.Terms)

    <button type="submit" id="btnSubmit" class="btn">Signup</button>
}

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>           
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>           

<script type="text/javascript">
    jQuery.validator.addMethod('shouldbetruemethod', function (value, element) {
        return $(element).is(':checked');
    }, '');

    jQuery.validator.unobtrusive.adapters.addBool('shouldbetrue', 'shouldbetruemethod');
</script>
@model MyViewModel
@使用(Html.BeginForm())
{
@CheckBoxFor(m=>m.Terms,新的{@class=“cb”})
条款及条件
@Html.ValidationMessageFor(x=>x.Terms)
报名
}
jQuery.validator.addMethod('shouldbetruemethod',函数(值,元素){
返回$(元素).is(':checked');
}, '');
jQuery.validator.unobtrusive.adapters.addBool('shouldbetrue','shouldbetruethod');

您是否缺少验证部分

@Html.ValidationFor(m => m.Terms)

要连接submit,请单击按钮或表单submit:

$(".btn").bind("click", function() {
    // Button was clicked, do stuff here
    return true; // so it can process the form submit
});

您始终可以使用:

@using(Html.BeginForm("Action", "Controller", new { @id = "myForm" }, FormMethod.Post, null)) {
...
}
并连接选择器Id

$("#myForm").bind("submit", function() { ... });

要将
复选框
与属性
Required
一起使用,您需要进行自定义验证,只需复制/粘贴即可,以了解为什么
[Required]
无法在框外工作,您需要了解输出HTML

jQuery验证中的required validation表示需要一个值,如:

<input type="text" value="" id="myTextbox" />

但在复选框的情况下,值始终存在

<input type="checkbox" value="Yes" id="myChackbox" checked="checked" />


因此,
必需的
总是正确的


您只需连接一个自定义事件,按照Darin的代码进行操作,然后就可以开始了。

您是否错过了验证部分

@Html.ValidationFor(m => m.Terms)

要连接submit,请单击按钮或表单submit:

$(".btn").bind("click", function() {
    // Button was clicked, do stuff here
    return true; // so it can process the form submit
});

您始终可以使用:

@using(Html.BeginForm("Action", "Controller", new { @id = "myForm" }, FormMethod.Post, null)) {
...
}
并连接选择器Id

$("#myForm").bind("submit", function() { ... });

要将
复选框
与属性
Required
一起使用,您需要进行自定义验证,只需复制/粘贴即可,以了解为什么
[Required]
无法在框外工作,您需要了解输出HTML

jQuery验证中的required validation表示需要一个值,如:

<input type="text" value="" id="myTextbox" />

但在复选框的情况下,值始终存在

<input type="checkbox" value="Yes" id="myChackbox" checked="checked" />


因此,
必需的
总是正确的


您只需连接一个自定义事件,按照Darin的代码进行操作,然后就可以开始了。

我会从您的模型中删除
术语,只需在页面中添加一个复选框,如下所示:

@using(Html.BeginForm()) {
...
<label>
    I agree to the terms & condition
    <input id="terms" type="checkbox" />
</label>
<button type="submit" id="btnSubmit" disabled="disabled" class="btn">Signup</button>
}

我会从您的模型中删除
术语
,只需在页面中添加一个复选框,如下所示:

@using(Html.BeginForm()) {
...
<label>
    I agree to the terms & condition
    <input id="terms" type="checkbox" />
</label>
<button type="submit" id="btnSubmit" disabled="disabled" class="btn">Signup</button>
}


您需要的事件是
onSubmit
如何从我在onSubmit中调用的函数中最终提交?我是否需要将某个值设置为true,然后提交到服务器以完成请求?您需要的事件是
onSubmit
如何最终从我在onSubmit中调用的函数提交?我是否需要将某个值设置为true,然后提交给服务器以完成请求?Darin,是否需要js代码的序列依赖项来注册它?我需要在$(document).ready(function(){})中调用它吗?@Projapati,我通常将所有脚本注册放在末尾,就在结束之前,并且不使用document.ready。我已经更新了我的答案,以提供一个更精确的示例,说明视图可能是什么样子。您唯一能做的就是在布局中使用一个名为scripts的部分,并在视图中覆盖该部分,以便将脚本包含在文档的末尾。这是javascript中为您指定的名称
jQuery.validator.unobtrusive.adapters.addBool('shouldbetrue'…
Darin,js代码是否有序列依赖项来注册它?我是否需要在$(document.ready)内调用它(函数(){})?@Projapati,我通常将我所有的脚本注册放在末尾,就在关闭
之前,并且不使用document.ready。我已经更新了我的答案,以提供一个更精确的视图示例。你唯一能做的就是在布局中使用一个名为scripts的部分,并依次覆盖视图中的此部分仅在文档末尾包含脚本。这是javascript中为您指定的名称。
jQuery.validator.unobtrusive.adapters.addBool('shouldbetrue'…
这是只针对复选框还是针对所有字段?它应该针对所有字段,否则它将不会编写所需的验证HTML。我不使用它,因为我不想使用jQuery验证。感谢您的详细说明。我将尝试此方法。更新后,您将了解代码在
复选框上执行的操作,我同意。如果未选中该复选框,则其值仍为false。在2方法自定义有效性属性vs自定义js挂钩中,建议使用哪一种?我将在其他视图中使用所需的复选框。这仅适用于复选框还是f