将ValidationAttribute与嵌套类一起使用

时间:2017-06-30 19:24:00

标签: c# asp.net asp.net-mvc asp.net-core-mvc

我的ViewModel中有以下类:

public class ParentClass
{
    public string Selection { get; set; }

    [MyValidation]
    public string ParentProperty { get; set; }

    public NestedClass Nested { get; set; }

    public class NestedClass
    {
        [MyValidation] //this doesn't have context of ParentClass inside MyValidation attribute
        public string NestedProperty { get; set; }
    }
}

以及以下ValidationAttribute:

public class MyValidation : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        ParentClass parentClass = (ParentClass)validationContext.ObjectInstance;

        if (parentClass.Selection.Equals("New"))
        {
            return new ValidationResult("Required");
        }

        return ValidationResult.Success;
    }
}

[MyValidation]可在ParentClass属性上正常使用。但是,当我把它放在NestedClass属性上时,我收到一个错误:

InvalidCastException: Unable to cast object of type 'NestedClass' to type 'ParentClass'.

我是否可以访问ParentClass.Selection内的[MyValidation]值,同时仍能将[MyValidation]置于NestedClass属性上?

0 个答案:

没有答案