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