有没有一种方法可以通过数据注释将 bool 属性设置为true?
public class MyAwesomeObj{
public bool ThisMustBeTrue{get;set;}
}
最佳答案
您可以创建自己的验证器:
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;
}
#endregion
}
关于asp.net-mvc - MVC模型要求为true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7717690/