如何在Data Annotation中创建自定义属性

时间:2011-10-23 05:34:01

标签: c# c#-4.0 attributes data-annotations custom-attributes

如何在数据注释中创建自定义属性?我想设置与属性广告相关的控件名称我找不到任何合适的属性。

我怎么能这样做?

感谢

1 个答案:

答案 0 :(得分:1)

您必须扩展System.ComponentModel.DataAnnotations.ValidationAttribute

ķ。 Scott Allen(OdeToCode)有一个很好的例子,他建立了一个自定义的“GreaterThan”属性。

http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx

以下是内联片段:

public class GreaterThanAttribute : ValidationAttribute
{
    public GreaterThanAttribute(string otherProperty)
        :base("{0} must be greater than {1}")
    {
        OtherProperty = otherProperty;
    }

    public string OtherProperty { get; set; }

    public override string FormatErrorMessage(string name)
    {            
        return string.Format(ErrorMessageString, name, OtherProperty);
    }

    protected override ValidationResult 
        IsValid(object firstValue, ValidationContext validationContext)
    {
        var firstComparable = firstValue as IComparable;
        var secondComparable = GetSecondComparable(validationContext);

        if (firstComparable != null && secondComparable != null)
        {
            if (firstComparable.CompareTo(secondComparable) < 1)
            {
                return new ValidationResult(
                    FormatErrorMessage(validationContext.DisplayName));
            }
        }               

        return ValidationResult.Success;
    }        

    protected IComparable GetSecondComparable(
        ValidationContext validationContext)
    {
        var propertyInfo = validationContext
                              .ObjectType
                              .GetProperty(OtherProperty);
        if (propertyInfo != null)
        {
            var secondValue = propertyInfo.GetValue(
                validationContext.ObjectInstance, null);
            return secondValue as IComparable;
        }
        return null;
    }
}