访问自定义数据注释中的依赖属性的简单方法

时间:2011-10-31 12:10:51

标签: .net asp.net-mvc-3 data-annotations

我的DomainRegistry型号上有以下属性:

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

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

域名是我的自定义数据注释,我尝试了IsValid方法的所有内容来访问扩展属性中的值。

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

[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方法中的扩展中获取值。任何人都有关于如何做到这一点的小费?另外,我需要将扩展​​名作为字符串值。

2 个答案:

答案 0 :(得分:5)

试试这个:

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;
    }

答案 1 :(得分:1)

IsValid方法的value参数包含带注释的属性的实际值,因此在您的情况下包含Name属性的值。要访问实际的DomainRegistry实例(以获取Extension属性的值),您应该使用validationContext.ObjectInstance属性:

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