asp.net-mvc - 防止继承模型中的验证属性

标签 asp.net-mvc inheritance validationattribute

我正在使用其他自定义联系人模型类继承的基本联系人模型。

public class BaseContactModel
{
    [Required(ErrorMessage = "Firstname is required")]
    public virtual string FirstName { get; set; }
}

基本联系人模型使用验证属性来标记某个属性是必需的,但在某些情况下我想覆盖或停止该属性。这可能吗?

public class ContactModel : BaseContactModel
{
    [NotRequired]
    public override string FirstName { get; set; }
}

我尝试使用新的验证属性 NotRequired 来返回 true,但似乎属性只是堆叠在一起,因此需要和 NotRequired 正在运行,并且验证失败。

在寻找解决方案(我找不到)时,我发现一些不相关的属性具有“继承”属性,但我在 System.ComponentModel.DataAnnotations< 的 native 验证属性中没有看到这一点/strong>.

这是一个失败的原因吗?我是否需要推出自己的版本来支持禁用继承?非常感谢任何帮助。

最佳答案

请参阅下面的内容,我创建了一个从另一个 BaseModel 继承的类 Model,使用 new 关键字,然后验证每个实例之一。据我所知,它们都使用基本属性。

为了清楚地说明验证例程,我添加了一个控制类 ControlModel

class Program
{
    static void Main(string[] args)
    {
        ValidationTest<Model>();
        ValidationTest<BaseModel>();
        ValidationTest<ControlModel>();

        Console.Read();
    }

    private static void WriteAttributeInfo<T>()
    {
        Console.WriteLine(string.Concat(typeof(T), " attributes:"));
        typeof(T).GetProperties().SelectMany(m => m.GetCustomAttributes(true)).Select(a => { Console.WriteLine(a); return a; }).ToList();
    }

    private static void ValidationTest<T>()
    {
        object obj = Activator.CreateInstance<T>();
        Console.WriteLine(string.Concat(typeof(T), " test: isValid = ", Validator.TryValidateObject(obj, new ValidationContext(obj, serviceProvider: null, items: null), new List<ValidationResult>())));
    }
}

class ControlModel
{
    public string FirstName { get; set; }

    public string Email { get; set; }
}

class BaseModel
{
    [RequiredAttribute]
    public virtual string FirstName { get; set; }

    [RequiredAttribute]
    public virtual string Email { get; set; }
}

class Model : BaseModel
{
    public new string FirstName { get; set; }

    public new string Email { get; set; }
}

ConsoleApplication1.Model 测试:isValid = False

ConsoleApplication1.BaseModel 测试:isValid = False

ConsoleApplication1.ControlModel 测试:isValid = True

从这个示例中,您似乎无法覆盖/隐藏/忽略继承的必需验证(尚未尝试其他)属性。

关于asp.net-mvc - 防止继承模型中的验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12788575/

相关文章:

c++ - 继承和模板函数c++

c# - ASP.NET Core 自定义验证属性未触发

c# - 在 C# MVC 中验证枚举值。发生部分验证 - 如何更改验证行为?

jquery - 将 json 数据从 Controller 传递到 View

ios - 如何使现有类成员成为协议(protocol)实现?

asp.net-mvc - 如何在 Web API ASP.Net core 中对异常过滤器进行单元测试。不想模拟 onException 方法

c# - 通用函数创建参数基的通用对象

c# - 测试覆盖 IsValid 的 ValidationAttribute

javascript - 为什么我的 jQuery.post() ajax 在我返回一个 View 时失败,但在我返回另一个 View 时却没有失败?

c# - 将参数(字符串)传递给 GetAsync()?