如果其他 属性 设置为 true,如何使用 mvc dataannotations 验证 属性 值?

How to use mvc dataannotations to validate property value if other property is set to true?

我正在尝试验证提交的表单,但我想验证一个 属性 仅当另一个 属性 设置为 true 时。

我的两个属性:

[DisplayName(Translations.Education.IsFeaturette)]
public  bool IsFeaturette { get; set; }

[DisplayName(Translations.Education.AddFeaturetteFor)]
[CusomValidatorForFeaturettes(IsFeaturette)]
public string[] Featurettes { get; set; }

自定义注释:

public class CusomValidatorForFeaturettes: ValidationAttribute
{
    private readonly bool _IsFeatturette;
    public CusomValidatorForFeaturettes(bool isFeatturette): base("NOT OK")
    {
        _IsFeatturette = isFeatturette;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null && _IsFeatturette )
        {
            var errorMessage = FormatErrorMessage(validationContext.DisplayName);
            return new ValidationResult(errorMessage);

        }
        return ValidationResult.Success;
    }
}

基本上,如果 isfeature 为真,那么特写必须有一个值!

获取错误:

An object reference is required for the non-static field, method, or property 'EducationViewModel.IsFeaturette'

我不能使这个 属性 静态,因为这会给我带来问题,因为这个 属性 是用实体框架设置的,我不想改变其中的任何一个。如何在不使 属性 静态的情况下完成此操作?

属性是在编译时添加到程序集的元数据中的,因此它的参数必须在编译时已知。生成错误是因为您将 属性 (bool IsFeaturette) 的值传递给非静态属性(它可能是 truefalse 在 运行-时间).

而是传递一个表示属性名称的字符串进行比较,并在方法中使用反射获取属性的值。

public  bool IsFeaturette { get; set; }

[CusomValidatorForFeaturettes("IsFeaturette")]
public string[] Featurettes { get; set; }

并将验证属性修改为

public class CusomValidatorForFeaturettes: ValidationAttribute
{
    private readonly string _OtherProperty;

    public CusomValidatorForFeaturettes(string otherProperty): base("NOT OK")
    {
        _OtherProperty = otherProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Get the dependent property 
        var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_OtherProperty);
        // Get the value of the dependent property 
        var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
        ......

然后您可以将 otherPropertyValue 转换为 bool 并进行条件检查。

我还建议您阅读 The Complete Guide to Validation in ASP.NET-MVC-3 Part-2 以更好地了解如何实现验证属性,包括如何实现 IClientValidatable 以便同时获得服务器端和客户端验证。我还建议您将方法重命名为(比如)RequiredIfTrueAttribute 以更好地反映它在做什么。

另请注意,foolproof 有大量用于 MVC 的验证属性。

最后一点,您当前的实现特定于对 属性(IsFeaturette 的值)的依赖,这对于验证属性来说毫无意义 - 您会更好关闭只是检查控制器中的值并添加 ModelStateError。上面的代码意味着您可以传入任何 属性 名称(只要 属性 是 typeof bool),这是验证属性应该允许的。