1

I have created an enum extension:

using System;
using System.ComponentModel;

namespace Shared.Enums.Extensions
{
    public static class EnumExtensions {

        // This extension method is broken out so you can use a similar pattern with 
        // other MetaData elements in the future. This is your base method for each.
        public static T GetAttribute<T>(this Enum value) where T : Attribute {
            var type = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
            return attributes.Length > 0 
                ? (T)attributes[0]
                : null;
        }

        // This method creates a specific call to the above method, requesting the
        // Description MetaData attribute.
        public static string ToName(this Enum value) {
            var attribute = value.GetAttribute<DescriptionAttribute>();
            return attribute == null ? value.ToString() : attribute.Description;
        }

    }
}

This allows me to add an attribute to my enum members so I can get a nicely formatted string to represent the emum to a user, using the ToName() extension method:

    public enum Rarity
    {
        [Description("One of a kind")]
        OneOfAKind,
        [Description("Rare Item")]
        RareItem
    }

// Then in my razor view

<dt>
    @Html.DisplayNameFor(model => model.Rarity)
</dt>
<dd>
    @Model.Rarity.ToName()
</dd>

Which works great!

So what I was hoping, was to use this description in the select drop down. But can't seem to figure out a way to do it in the Razor view, using the HTML.Helpers. Where would I put the logic for calling the ToName() extension method?:

<div class="form-group">
    <label asp-for="Rarity" class="control-label"></label>
    <select asp-for="Rarity"
       asp-items="Html.GetEnumSelectList<Rarity>()" class="form-control"></select>
</div>
Mark Johnson
  • 575
  • 4
  • 20

1 Answers1

1

You want to use System.DataAnnotations.Display name rather than description. As per this answer: Html.GetEnumSelectList - Getting Enum values with spaces

Craig
  • 390
  • 3
  • 13