8

我有几个属性的集合,这些属性都应该始终一起用于 UI 和验证。例如对于货币字段,我必须添加 UI 提示、验证逻辑和显示格式。结果,我的班级看起来很拥挤。

public class Model
{
    [UIHint("Currency")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:C}")]
    [CustomRegularExpression(Currency.ValidationPattern, OnlyOnClientSide = true)]
    [SetMetaDataForCustomModelBinder("Currency")]
    public double? Cost { get; set; }

    [UIHint("Currency")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:C}")]
    [CustomRegularExpression(Currency.ValidationPattern, OnlyOnClientSide = true)]
    [SetMetaDataForCustomModelBinder("Currency")]
    public double? Profit { get; set; }
}

有没有办法创建一个[Currency]属性,将所有这些属性的功能组合成一个简单的属性?我的目标是创建以下内容:

public class Model
{
    [Currency] public double? Cost { get; set; }
    [Currency] public double? Profit { get; set; }
}

编辑:为了澄清,我尝试创建一个自定义属性,但没有公开的接口允许我实现这些不同属性的功能。我可以继承 ValidationAttribute,但我也不能继承 UIHintAttribute。我还缺少任何其他潜在的解决方案吗?

4

1 回答 1

3

根据帖子和帖子对 Phil Haack文章的引用,您可以创建自定义AssociatedMetadataProvider添加所需的属性。你会有这样的东西:

public class MyCustomMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var attributeList = attributes.ToList();
        if (attributeList.OfType<CurrencyAttribute>().Any())
        {
            attributeList.Add(new UIHintAttribute("Currency"));
            attributeList.Add(new DisplayFormatAttribute
            {
                ApplyFormatInEditMode = true, 
                DataFormatString = "{0:C}"
            });
        }

        return base.CreateMetadata(attributeList, containerType, modelAccessor, modelType, propertyName);
    }
}

在应用程序启动事件中:

ModelMetadataProviders.Current = new MyCustomMetadataProvider();
于 2013-02-13T20:51:40.047 回答