强制执行模式的布尔值,使用数据的注释是真实的 [英] Enforcing a model's boolean value to be true using data annotations

查看:163
本文介绍了强制执行模式的布尔值,使用数据的注释是真实的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题,在这里(我认为)。

我有在底部,用户必须同意的条款和条件复选框的形式。如果用户不选中该复选框,我想一个错误信息与其他形式的错误一起显示在我的验证摘要。

我说这我的视图模型:

  [必需]
[范围(1,1,的ErrorMessage =你必须同意条款和条件)]
公共BOOL AgreeTerms {搞定;组; }

但是,这并不能正常工作。

有没有一种简单的方法来强制值与数据的注解真的吗?


解决方案

 使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations;
使用System.Threading.Tasks;
使用System.Web.Mvc;命名空间Chec​​ked.Entitites
{
    公共类BooleanRequiredAttribute:ValidationAttribute,IClientValidatable
    {
        公众覆盖BOOL的IsValid(对象的值)
        {
            返回值= NULL&放大器;!&安培; (布尔)值==真;
        }        公共IEnumerable的< ModelClientValidationRule> GetClientValidationRules(ModelMetadata元,ControllerContext上下文)
        {
            //返回新ModelClientValidationRule [] {新ModelClientValidationRule(){ValidationType =booleanrequired的ErrorMessage = this.ErrorMessage}};
            产量返回新ModelClientValidationRule()
            {
                ValidationType =booleanrequired
                的ErrorMessage = this.ErrorMessageString
            };
        }
    }
}

Simple problem here (I think).

I have a form with a checkbox at the bottom where the user must agree to the terms and conditions. If the user doesn't check the box, I'd like an error message to be displayed in my validation summary along with the other form errors.

I added this to my view model:

[Required]
[Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")]
public bool AgreeTerms { get; set; }

But that didn't work.

Is there an easy way to force a value to be true with data annotations?

解决方案

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Checked.Entitites
{
    public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value != null && (bool)value == true;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };
            yield return new ModelClientValidationRule() 
            { 
                ValidationType = "booleanrequired", 
                ErrorMessage = this.ErrorMessageString 
            };
        }
    }
}

这篇关于强制执行模式的布尔值,使用数据的注释是真实的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆