【问题标题】:How to require a checkbox to be checked at client side before form gets submitted to server in MVC 3?在 MVC 3 中将表单提交到服务器之前,如何要求在客户端检查复选框?
【发布时间】:2011-06-21 08:09:36
【问题描述】:

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

有人知道如何正确地做吗?

我正在使用 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, new { @class = "cb" }) Terms & Condition
<button type="submit" id="btnSubmit" class="btn">Signup</button>

另外, 单击提交按钮时是否可以调用/捕获某些 JS 函数? 这样我可以很容易地使用 jquery 进行验证然后提交?

感谢阅读

【问题讨论】:

  • 你需要的事件是onSubmit
  • 我如何最终从我在 onSubmit 中调用的函数提交?我是否需要将某些内容设置为 true,然后将其提交给服务器以完成请求?

标签: jquery asp.net-mvc-3 validation


【解决方案1】:

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

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

用来装饰你的模型:

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

最后在视图中注册它:

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

【讨论】:

  • 达林,注册的js代码有顺序依赖吗?我需要在 $(document).ready(function () {}) 中调用它吗?
  • @Projapati,我通常将我所有的脚本注册放在最后,就在结束 &lt;/body&gt; 之前,并且不要使用 document.ready。我已经更新了我的答案,以提供一个更精确的示例来说明视图的外观。您唯一能做的就是在布局中使用一个称为脚本的部分,并在视图中覆盖该部分,以便将脚本包含在文档的末尾。
  • 这是您将在 javascript 中分配的名称。 jQuery.validator.unobtrusive.adapters.addBool('shouldbetrue' ...
【解决方案2】:

我会从您的模型中删除 Terms,然后像这样在页面中添加一个复选框:

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

并将事件处理程序附加到更改事件以切换您的提交按钮。

$('#terms').change(function() {
    if($(this).is(':checked')) {
        $(this).siblings('button[type="submit"]').removeAttr('disabled');
    } else {
        $(this).siblings('button[type="submit"]').attr('disabled', 'disabled');
    }
});

【讨论】:

  • 但是大卫,如果复选框是只读的,它如何切换提交按钮?或者您的意思是禁用提交 btn?
  • 这有轻微的可用性问题。用户可能想知道为什么单击提交按钮不起作用?否则OK
  • 或者,您可以处理提交并检查是否已检查。
【解决方案3】:

你没有错过验证部分吗?

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

挂钩提交就是挂钩,要么是按钮点击,要么是表单提交:

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

$("form").bind("submit", function() {
    // Form was submitted, do stuff here
    return true; // so it can process the form submit to the server (return false if you dont want to submit)
});

您可以随时使用:

@using(Html.BeginForm("Action", "Controller", new { @id = "myForm" }, FormMethod.Post, null)) {
...
}

并与 Selector Id 挂钩

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

要将CheckBoxRequired 属性一起使用,您需要进行自定义验证,只需复制/粘贴Darin's code,以了解为什么[Required] 无法开箱即用您需要了解输出 HTML

jQuery Validation 中的 required validation 表示需要一个值,例如:

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

但如果是复选框,则始终存在一个值

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

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

所以Required 总是正确的。

您只需要连接一个自定义事件,按照 Darin 的代码就可以开始了。

【讨论】:

  • 这仅适用于复选框还是适用于所有字段?
  • 它应该存在于所有字段中,否则它不会编写所需的验证 HTML。我不使用它,因为我不想使用 jQuery 验证。
  • 感谢您的详细说明。我会试试这个。
  • 已更新,以便您了解代码在 checkbox 上的作用
  • 我同意。如果未选中该复选框,它的值仍然为 false。在自定义 valition 属性与自定义 js 挂钩的 2 种方法中,推荐哪一种?我将在其他需要的视图中有复选框。
猜你喜欢
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 2015-02-24
  • 2021-03-13
相关资源
最近更新 更多