合并数据注释属性

时间:2013-02-12 16:40:16

标签: asp.net-mvc validation

我有一些属性的集合,这些属性应该总是一起用于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子类化。我还缺少其他任何可能的解决方案吗?

1 个答案:

答案 0 :(得分:3)

根据post以及来自Phil Haack article的帖子的引用,您可以创建自定义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();