Mat*_*ell 8 validation asp.net-mvc
我有一些属性的集合,这些属性应该总是一起用于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; }
}
Run Code Online (Sandbox Code Playgroud)
有没有办法创建一个[Currency]属性,将所有这些属性的功能组合成一个简单的属性?我的目标是创建以下内容:
public class Model
{
[Currency] public double? Cost { get; set; }
[Currency] public double? Profit { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
编辑:为了澄清,我已经尝试创建自定义属性,但没有暴露的接口允许我实现这些不同属性的功能.我可以继承ValidationAttribute,但是我也不能将UIHintAttribute子类化.我缺少任何其他潜在的解决方案?
根据该帖子以及该帖子对 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);
}
}
Run Code Online (Sandbox Code Playgroud)
并在应用程序启动事件中:
ModelMetadataProviders.Current = new MyCustomMetadataProvider();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1502 次 |
| 最近记录: |