在自定义数据批注中访问依赖属性的简单方法 [英] Simple way of accessing dependent property inside custom data annotation

查看:48
本文介绍了在自定义数据批注中访问依赖属性的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 DomainRegistry 模型具有以下属性:

I have the following properties on my DomainRegistry model:

    [Domain("Extension")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Select extension")]
    public string Extension { get; set; }

请确保这是我的自定义数据注释,并且我已经尝试过 IsValid 方法上的所有内容来访问扩展属性内的值.

Domain it's my custom data annotation and I've tryed everything on my IsValid method to access the value inside extension property.

自定义数据注释中包含以下内容:

I have the following in my custom data annotation:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DomainAttribute : ValidationAttribute
{
    public string ExtensionProperty { get; set; }

    public DominioAttribute(string property)
    {
        ExtensionProperty = property;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
        var extension = (string) properties.Find(Propriedade, true).GetValue(value);
        if (extension == null) return new ValidationResult("Extension shouldn't be null");
        return null;
    }

我似乎无法从 IsValid 方法中的扩展获取值.有人对如何做到这一点有任何建议吗?另外,我需要将扩展​​名作为字符串值.

I can't seem to get the value from extension inside IsValid method. Anyone have any tip on how to do that? Also I need to get extension as a string value.

推荐答案

尝试一下:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var containerType = validationContext.ObjectInstance.GetType();
        var field = containerType.GetProperty("Extension");

        if (field != null)
        {
            var extensionValue = field.GetValue(validationContext.ObjectInstance, null);

            return extensionValue != null ? ValidationResult.Success : new ValidationResult("Extension shouldn't be null", new[] { validationContext.MemberName });
        }

        return ValidationResult.Success;
    }

这篇关于在自定义数据批注中访问依赖属性的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆