zoukankan      html  css  js  c++  java
  • 在ASP.NET MVC中验证checkbox 必须选中 (Validation of required checkbox in Asp.Net MVC)

    转载自 http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/

    Why would you want to have a required checkbox, i.e. a checkbox that user would have to check? Well, a typical example would be that you have some sort of terms associated with submitting a form that the user has to agree to.

    You might think that decorating a boolean property on one of your MVC models with a RequiredAttribute, would mean that if you presented that property in your view as a checkbox, that would require the user to click that checkbox before submitting the form. This is not the case however. If you take a look at the implementation of the RequiredAttribute it is actually casting the value to validate into a string and checking the string length. If it can’t cast the value to a string, it will just return true for IsValid.

    It is quite easy however to create your own custom validation attribute that you could decorate your boolean property with. The following code checks if the decorated property is a bool, and if so, requires it to have been set to true;

    public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            if (value is bool)
                return (bool)value;
            else
                return true;
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
            ModelMetadata metadata,
            ControllerContext context)
        {
            yield return new ModelClientValidationRule
                                {
                                    ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                                    ValidationType = "booleanrequired"
                                };
        }
    }

    Notice the GetClientValidationRules-method above where we specify the error message to display if client-side validation fails, and what the validation type is. The value we provide as the validation type will be rendered as the name of the rule in the HTML element, and will be used further down to tell jQuery how to validate this property.

    After creating the new validation attribute, we need to apply it to a boolean property on out model;

    [BooleanRequired(ErrorMessage = "You must accept the terms and conditions.")]
    [Display(Name = "I accept the terms and conditions")]
    public bool TermsAndConditionsAccepted { get; set; }

    Next, create a simple view with a form that includes you boolean property;

    @model MyModel@using (Html.BeginForm())
    {
        <fieldset>
            <legend>Terms and Conditions</legend>
            @Html.ValidationSummary(true, "Please correct the errors and try again.")
            <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                Fusce facilisis ullamcorper consequat. Vestibulum non sapien lectus.
                Nullam at quam eu sapien mattis ultrices.
            </p>
            <ol>
                <li>
                    @Html.CheckBoxFor(m => m.TermsAndConditionsAccepted)
                    @Html.LabelFor(m => m.TermsAndConditionsAccepted, new { @class = "checkbox" })
                    @Html.ValidationMessageFor(m => m.TermsAndConditionsAccepted)
                </li>
            </ol>
            <input type="submit" value="Submit" />
        </fieldset>
    }

    Lastly, in order for client-side validation to work, you need to include the following script in your view (or you can just put line 3 in a javascript file that you reference);

    <script type="text/javascript">
        (function ($) {
            $.validator.unobtrusive.adapters.addBool("booleanrequired", "required");
        } (jQuery));
    </script>

    This just registers a new validation adapter for the boolean required attribute, where the first parameter is the adapter name and the second parameter is the name of jQuery validate rule. The adapter name should match the value we specified earlier as the validation type, and the jQuery validation required-rule will require the user to check the checkbox.

    That’s it! This will make sure that the checkbox is checked by the user client-side (using jQuery unobtrusive validation*) and that the boolean property is set to true server-side when the form is submitted to the server.

    *The ClientValidationEnabled and UnobtrusiveJavaScriptEnabled application settings must be set to true in your web.config for client-side validation to work.

  • 相关阅读:
    Azure 媒体服务的 RTMP 支持和实时编码器
    在_Linux_中如何使用_gdb_调试_C_程序
    你刚吃的兰州牛肉面,背后就藏着大数据
    《C++覆辙录》——1.9:使用糟糕的语言
    老司机带你用MaxCompute和表格存储玩转车联网数据
    快速部署rabbitMQ教程
    《第一本Docker书(修订版)》——1.3 能用Docker做什么
    《第一本Docker书(修订版)》——第1章_简介_1.1Docker简介
    【DockerCon2017最新技术解读】Docker最新特性介绍
    【DockerCon2017最新技术解读】如何在阿里云一键部署高可用的Kubernetes集群
  • 原文地址:https://www.cnblogs.com/wphl-27/p/6084178.html
Copyright © 2011-2022 走看看