asp.net-mvc - MVC模型要求为true

标签 asp.net-mvc data-annotations

有没有一种方法可以通过数据注释将 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/

相关文章:

asp.net-mvc - MVC Razor 表单提交不工作

asp.net-mvc - ASP.NET MVC 中的自动完成组合框?

asp.net-mvc-3 - 如何将一个属性的值包含在另一个属性的验证错误消息中?

c# - DisplayFormat 与 CultureInfo DateTime

asp.net-mvc - 数据类型客户端验证在 MVC 2 中不起作用

.net - 使用 ASP.Net MVC 将图像上传到 SQL Server 2005?

javascript - "Tag is missing a name"带 Razor

jquery - 更新 jQuery 中的 HiddenFor,然后将新值提交到 Controller

c# - 继承 View 模型和更改 DisplayName 数据注释

asp.net-mvc - 在 asp.net mvc 中设置来自 Controller 的动态数据注释错误消息