如何在数据注释中创建自定义属性
本文关键字:创建 自定义属性 注释 数据 | 更新日期: 2023-09-27 18:12:11
如何在数据注释中创建自定义属性?我想设置与属性相关联的控件名称,但我没有找到任何合适的属性。
我该怎么做?
谢谢
必须扩展System.ComponentModel.DataAnnotations.ValidationAttribute
K。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;
}
}