Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.GetEnumSelectList - Getting Enum values with spaces

I was using asp-items="@Html.GetEnumSelectList(typeof(Salary))" in my Razor view with a select tag, to populate the list values based on the enum Salary.

However, my enum contains some items which I would like to have spaces within. E.g. one of the items is PaidMonthly, but when I display this using Html.GetEnumSelectList, I would like it to be displayed as "Paid Monthly" (with a space in it)

I tried using the Description attribute over each member in the enum, however when the select box renders it uses the raw value only.

Can anyone please help me out with this matter?

(My Code sample) -> Using ASP.NET Core 1.0

Razor View:

<select asp-for="PersonSalary" asp-items="@Html.GetEnumSelectList(typeof(Enums.Salary))">
</select>

Enum Salary:

public enum Salary
{
    [Description("Paid Monthly")]
    PaidMonthly = 1,
    PaidYearly = 2
} 
like image 918
terry45 Avatar asked Oct 14 '16 22:10

terry45


People also ask

Can enum values have spaces?

Normally, the name of an enum in c# can't contain any special characters or spaces. There can be situations where we need to use friendly names for enums which have spaces in between. You will get syntax error since this is not the correct way of enum declaration.

Can enum names have spaces?

Sometimes you might need to loop on the elements of a particular enum and print its element names, however as you know by the language constraints, the enum element names must follow the naming convention, you cannot include spaces or other special characters.


Video Answer


1 Answers

I managed to solve it. I just had to use the other method of GetEnumSelectList<>, and in the Razor view we need to use the Display attribute.

Here is the code:

Razor View:

<select asp-for="PersonSalary" asp-items="Html.GetEnumSelectList<Enums.Salary>()"></select>

Enum Salary:

public enum Salary
{
    [Display(Name="Paid Monthly")]
    PaidMonthly = 1,
    PaidYearly = 2
} 
like image 175
terry45 Avatar answered Sep 19 '22 20:09

terry45