我有一个表单,其中一些字段带有必填
数据注释,然后我有一个带有数据注释的“接受条款和条件”复选框[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/