c# - 从自定义验证器中验证上下文的基本类型获取值

标签 c# validation asp.net-mvc-4 c#-4.0

我正在尝试编写自己的验证属性,但我无法从继承的类中获取属性的值。这是我的代码:

protected override ValidationResult IsValid(object value, ValidationContext context)
{
    if (context.ObjectType.BaseType == typeof(AddressModel))
    {
        PropertyInfo property = context.ObjectType.BaseType.GetProperty(_propertyName);

        // this is the line i'm having trouble with:
        bool isRequired = (bool)property.GetValue(context.ObjectType.BaseType); 

        return base.IsValid(value, context);
    }

    return ValidationResult.Success;
}

我不知道我要传递给 GetValue 的内容是什么?因为它期待一个对象,但我传入的所有内容都给了我一个 属性类型与目标不匹配 异常(exception)

当我试图从继承的类和 context.ObjectInstance 中获取属性的值时,我不得不转到基本类型。不包括必要的属性

最佳答案

您可以简单地将您的对象转换为 AddressModel并像那样使用它。

protected override ValidationResult IsValid(object value, ValidationContext context)
{
    var addressModel = context.ObjectInstance as AddressModel
    if (addressModel != null)
    {
        // Access addressModel.PROPERTY here

        return base.IsValid(value, context);
    }

    return ValidationResult.Success;
}
context.ObjectInstance属于 object type 而不是模型的类型,因为验证框架不是为了显式验证模型而创建的,但它是正确的对象实例。投出后就可以正常使用了。

作为旁注,您收到 property.GetValue(context.ObjectType.BaseType) 错误的原因是因为 GetValue方法需要您正在调用其属性的对象的实例。

关于c# - 从自定义验证器中验证上下文的基本类型获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21629167/

相关文章:

c# - 单击通知图标时如何以编程方式显示上下文菜单?

c# - 检查集合中的项目是否与任何其他项目匹配的 Linq 方法

c# - MVC5 客户端验证未启动

php - 验证预约表

asp.net-mvc-3 - 很难获取有关在 Orchard View 中工作的权限的条件代码

c# - 有什么方法可以让 visual studio 忽略使用未分配对象的编译错误?

c# - SQL Server + Entity Framework 基础知识

javascript - 使用 Aurelia 对 Blur 进行现场验证

c# - 将actionresult的返回值转移到另一个 View

asp.net-mvc-4 - Web API帮助页面-自定义属性文档