asp.net mvc - Combine data annotation attributes -
i have collection of several attributes should used ui , validation. illustration currency field, have add together ui hint, validation logic, , display formatting. result, class looks crowded.
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? turn a profit { get; set; } }
is there way create [currency]
attribute combines functionality of these attributes 1 simple attribute? goal create following:
public class model { [currency] public double? cost { get; set; } [currency] public double? turn a profit { get; set; } }
edit: clarify, have tried creating custom attribute, there no interfaces exposed allow me implement functionality of different attributes. can subclass validationattribute, cannot subclass uihintattribute. other potential solutions i'm missing?
according post , reference post phil haack's article can create custom associatedmetadataprovider
adds attributes need. have this:
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}" }); } homecoming base.createmetadata(attributelist, containertype, modelaccessor, modeltype, propertyname); } }
and in application start event:
modelmetadataproviders.current = new mycustommetadataprovider();
asp.net-mvc validation
No comments:
Post a Comment