asp.net-coreenumsasp.net-core-tag-helpersdisplayname-attribute

Binding a SelectTagHelper to an Enum, using Display(Name) for SelectList (yet persisting string Value instead of int)


(WPF dev here, new to web apps)

In my DB, I have a field containing strings. For simplicity, let's pretend the strings denote countries. The strings contain spaces (e.g. "United States").

I need to provide a way to update that field for a given record.

I was planning on using EnumMemberAttribute [EnumMember(Value = "United States")] to persist a string, not an int, to the DB (to prevent trouble when adding an enum item, and to facilitate readabilty - also because new records-with-strings will be inserted in batch regularly, would require casting in order to be stored as ints, and might include other options / spelling mistakes in the future).

I made an Enum, but I can't get my SelectTagHelper to select the proper item for any given record. The first item ("") is selected instead.

public enum CountryEnum
{
    [Display(Name="")]
    None,
    [Display(Name = "United States of America")]
    USA,
    [Display(Name = "Great Britain")]
    UK
}

My SelectTagHelper:

<select asp-for="SelectedRecord.Country" asp-items="Html.GetEnumSelectList<MyApp.Models.CountryEnum>()">


Solution

  • My bad: I was using the Enum in a class, but failed to declare it as such: the property was a string, not (an instance of) my Enum.

    public class Employee
    {
        public string Country {get; set;}
    }
    

    (Morale: don't code while ill)