MVC模式需要真实 [英] MVC Model require true

查看:127
本文介绍了MVC模式需要真实的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有通过数据注释的方式来要求一个布尔值属性设置为true?

 公共类MyAwesomeObj {
    公共BOOL ThisMustBeTrue {获取;设置;}
}


解决方案

您可以创建自己的验证:

 公共类IsTrueAttribute:ValidationAttribute
{
    ValidationAttribute的#区域覆盖    ///<总结>
    ///确定对象的指定的值是否有效。
    ///< /总结>
    ///<退货和GT;
    ///如果指定的值是有效的;否则为false。
    ///< /回报>
    ///< PARAM NAME =值>在指定验证对象的价值上的<见CREF =T:System.ComponentModel.DataAnnotations.ValidationAttribute/>声明。
    ///< /参数>
    公众覆盖BOOL的IsValid(对象的值)
    {
        如果(价值== NULL)返回false;
        如果(!value.GetType()= typeof运算(布尔))抛出新的InvalidOperationException异常(只能在布尔属性使用。);        回报(布尔)值==真;
    }    #endregion
}

Is there a way through data annotations to require that a boolean property be set to true?

public class MyAwesomeObj{
    public bool ThisMustBeTrue{get;set;}
}

解决方案

You could create your own validator:

public class IsTrueAttribute : ValidationAttribute
{
    #region Overrides of ValidationAttribute

    /// <summary>
    /// Determines whether the specified value of the object is valid. 
    /// </summary>
    /// <returns>
    /// true if the specified value is valid; otherwise, false. 
    /// </returns>
    /// <param name="value">The value of the specified validation object on which the <see cref="T:System.ComponentModel.DataAnnotations.ValidationAttribute"/> is declared.
    ///                 </param>
    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;
    }

    #endregion
}

这篇关于MVC模式需要真实的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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