I've got a property in my model called "Promotion" that its type is a flag enum called "UserPromotion". Members of my enum have display attributes set as follows:
[Flags]
public enum UserPromotion
{
None = 0x0,
[Display(Name = "Send Job Offers By Mail")]
SendJobOffersByMail = 0x1,
[Display(Name = "Send Job Offers By Sms")]
SendJobOffersBySms = 0x2,
[Display(Name = "Send Other Stuff By Sms")]
SendPromotionalBySms = 0x4,
[Display(Name = "Send Other Stuff By Mail")]
SendPromotionalByMail = 0x8
}
Now I want to be able to create say a ul in my view to show the selected values of my "Promotion" property. This is what I have done so far but the problem is that how can I get the display names here?
<ul>
@foreach (int aPromotion in @Enum.GetValues(typeof(UserPromotion)))
{
var currentPromotion = (int)Model.JobSeeker.Promotion;
if ((currentPromotion & aPromotion) == aPromotion)
{
<li>Here I don't know how to get the display attribute of "currentPromotion".</li>
}
}
</ul>
Based on previous answers I've created this comfortable helper to support all DisplayAttribute properties in a readable way:
Building on Aydin's great answer, here's an extension method that doesn't require any type parameters.
NOTE: GetName() should be used instead of the Name property. This ensures that the localized string will be returned if using the ResourceType attribute property.
Example
To use it, just reference the enum value in your view.
Output
Promotion: Send Job Offers By Mail
I want to contribute with culture-dependent GetDisplayName enum extension. Hope this will be usefull for anyone googling this answer like me previously:
"standart" way as Aydin Adn and Todd mentioned:
"Culture-dependent" way:
Based on Aydin's answer I would suggest a less "duplicatious" implementation (because we could easily get the
Type
from theEnum
value itself, instead of providing it as a parameterWith Core 2.1,