Is it possible to override the required attribute on a property in a model?

后端 未结 5 1443
迷失自我
迷失自我 2020-12-06 04:35

I\'m curious to find out if it is possible to override the [Required] attribute that has been set on a model. I\'m sure there most be a simple solution to this problem, any

5条回答
  •  鱼传尺愫
    2020-12-06 04:57

    @HackedByChinese method is fine, but it contains a problem

    public class BaseModel
    {
        [Required]
        public string RequiredProperty { get; set; }
    }
    
    public class DerivativeModel : BaseModel
    {
        new public string RequiredProperty { get; set; }
    }
    

    This code give you a validation error in ModelState EVEN if you use DerivativeModel on the form, override doesn't work either, so you cannot delete Required attribute by overriding or renewin it, so I came to a some sort of a workaround

    public class BaseModel
    {
        public virtual string RequiredProperty { get; set; }
    }
    
    public class DerivativeModel : BaseModel
    {
        [Required]
        public override string RequiredProperty { get; set; }
    }
    
    public class DerivativeModel2 : BaseModel
    {
        [Range(1, 10)]
        public override string RequiredProperty { get; set; }
    }
    

    I have a base model with no validation attributes and derived classes

提交回复
热议问题