c# - ASP.NET MVC : Why Range Data Annotation is not working on checkbox in client side?

标签 c# asp.net-mvc asp.net-mvc-4 data-annotations

我有一个表单,其中一些字段带有必填数据注释,然后我有一个带有数据注释的“接受条款和条件”复选框[Range(typeof(bool), "true", "true", ErrorMessage="您必须接受条款和条件才能继续")] 一切正常,但令人烦恼的是 Required 数据注释在发布之前触发错误。我的意思是,我单击提交,表单不会发布帖子,它会显示错误,但是使用范围,表单发布,然后显示错误。

这是为什么呢?这是一种常见行为吗?

最佳答案

我终于找到了这个解决方案:

public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            if (value == null) return false;
            if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
            return (bool)value == true;
        }

        public override string FormatErrorMessage(string name)
        {
            return "The " + name + " field must be checked in order to continue.";
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
                ValidationType = "enforcetrue"
            };
        }
    }

在我的 JS 中:

jQuery.validator.addMethod("enforcetrue", function (value, element, param) {
            return element.checked;
        });
        jQuery.validator.unobtrusive.adapters.addBool("enforcetrue");

关于c# - ASP.NET MVC : Why Range Data Annotation is not working on checkbox in client side?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290465/

相关文章:

c# - GPS 与 Entity Framework 和 LINQ 协调

c# - Css 每行显示 3 个 foreach 结果

c# - JSON.Net 为所有消息解析 Facebook Graph JSON

asp.net-mvc - 使用 html.ActionLink 时如何在我的网址中添加 "#"

c# - 将 Entity Framework 4.4 与 Mysql 结合使用

c# - 模型类属性字符串长度为 nvarchar max

C#:通过内存有效搜索200万个对象,而无需外部依赖

c# - comboBox 中的 selectedIndex 在某些情况下不返回正确的整数

html - 使用 CSS 动态调整表格中的 div 大小

c# - HowTo : Using MvcContrib. 不使用 MvcContrib.Grid View 的分页