c# - DataAnnotations: read out the Name property in code -
i have decorated following enum display dataannotation attributes:
public enum requiredoptions { [display(name="optional",description ="optional")] optional, [display(name="not used",description ="not used")] notused, [display(name="required",description ="required")] required }
i'd read out name value of display attribute given enum value in code. how do this?
public static string displayrequiredoptionname(requiredoptions opt) { // return value of name display attribute opt }
well, after doing digging in mvc source code (see src\system.web.mvc\html\selectextensions.cs, see getdisplayname()), here's got work:
public static string getenumdisplayname<t>(t enuminstance) { return getdisplayname(enuminstance.gettype().getfield(enuminstance.tostring())); } private static string getdisplayname(fieldinfo field) { displayattribute display = field.getcustomattribute<displayattribute>(inherit: false); if (display != null) { string name = display.getname(); if (!string.isnullorempty(name)) { return name; } } return field.name; }
Comments
Post a Comment