How to get the Display Name Attribute of an Enum member via MVC Razor code?

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How to get the Display Name Attribute of an Enum member via MVC Razor code?

How to Get the Display Name Attribute of an Enum Member via MVC Razor Code? 😎💻

Have you ever found yourself in a situation where you needed to display the display name attribute of an enum member in your MVC Razor code? 🤔 Fear not! In this blog post, we'll dive into a common issue faced by developers and provide you with easy solutions to retrieve and display the enum member's display name attribute. 💪

The Problem: Getting the Display Names of Enum Members 🎭

Imagine you have a model property called Promotion, and its type is a flag enum named UserPromotion. Each member of the UserPromotion enum has a display attribute assigned to it, which specifies how the member should be displayed.

[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, let's say you want to create a <ul> in your Razor view to show the selected values of the Promotion property. The challenge is figuring out how to retrieve and display the display names of each selected UserPromotion enum member.

Solution: Using MVC Razor Code to Get Display Names 🌟

To solve this problem, we can utilize the powerful MVC Razor code to access the display name attribute of each enum member. Here's how you can do it step-by-step:

  1. Inside your Razor view, create a <ul> element to hold the list of selected values.

<ul>
    @foreach (int aPromotion in Enum.GetValues(typeof(UserPromotion)))
    {
        var currentPromotion = (int)Model.JobSeeker.Promotion;
        if ((currentPromotion & aPromotion) == aPromotion)
        {
            // Display the display name attribute of the current promotion
        }
    }
</ul>
  1. To get the display name attribute of the current UserPromotion enum member, you can use the DisplayAttribute class provided by .NET.

<ul>
    @foreach (int aPromotion in Enum.GetValues(typeof(UserPromotion)))
    {
        var currentPromotion = (int)Model.JobSeeker.Promotion;
        if ((currentPromotion & aPromotion) == aPromotion)
        {
            var displayAttribute = typeof(UserPromotion).GetMember(Enum.GetName(typeof(UserPromotion), aPromotion))
                .FirstOrDefault()?.GetCustomAttributes(typeof(DisplayAttribute), false)
                .FirstOrDefault() as DisplayAttribute;

            <li>@displayAttribute?.Name</li>
        }
    }
</ul>

By using the GetMember() method in conjunction with GetCustomAttributes(), we can access the display attribute of the current enum member and retrieve its display name.

  1. Finally, we can display the enum member's display name by using the @displayAttribute?.Name syntax in Razor.

Conclusion and Call-to-Action 🏁🙌

Congratulations! You've learned how to retrieve and display the display name attribute of an enum member in your MVC Razor code. Now you can easily create a list of selected enum values that are user-friendly and meaningful to your users. 🎉

If you found this blog post helpful, make sure to share it with your developer friends who might benefit from it. And don't forget to subscribe to our newsletter for more helpful tech tips and tricks! 💌👨‍💻

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my