c# - Compare attribute does not use Display attribute of compared property -
i have viewmodel used changing password, , uses compare
dataannotation so:
[display(name = "new password")] public string new { get; set; } [compare("new")] [display(name = "confirm password")] public string confirmpassword { get; set; }
unfortunately compare
attribute not utilize display
attribute of compared property.
the error message displays as
'confirm password' , 'new' not match.
which can see uses comparing property's display
attribute, not compared property's.
i'll specify don't want use errormessage
parameter because i'd hard-coding property name rather acquiring existing attribute. i'd keep solution best-practice possible.
how can make compare
attribute utiliize display
attribute of compared property?
i think may issue compare attribute, since can see otherdisplayname attribute in list of properties, , correctly uses display name property decorating ("confirm password" , not "confirmpassword").
one work around have found create new class inherits compareattribute, so:
public class comparewithdisplayname : compareattribute { public comparewithdisplayname(string otherproperty) : base(otherproperty) { } }
then use on property:
[display(name = "new password")] public string new { get; set; } [display(name = "confirm password")] [comparewithdisplayname("new")] public string confirmpassword { get; set; }
i have no idea why works. reflection or order in works out each property's display attribute is. creating custom version of it, perhaps ordering changed? either way, did trick me :)
edit 2 sorry, forgot add part needed client side validation, explained here. can either add in global.asax.cs file:
dataannotationsmodelvalidatorprovider.registeradapter(typeof(comparewithdisplayname), typeof(compareattributeadapter))
or implement iclientvalidatable interface on custom attribute. both of these shown in link
Comments
Post a Comment