20

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
} 
7
  • Show the code you have tried Commented Oct 14, 2016 at 22:21
  • Try with [Display(Name = "Paid Monthly")] Commented Oct 14, 2016 at 22:30
  • Actually, I did try that too. Doesn't work though :\ Commented Oct 14, 2016 at 22:32
  • Try what Stephen said then use @Html.EnumDropDownListFor(model => model.Salary), assuming your list is a dropdown list... Commented Oct 14, 2016 at 22:34
  • Hi Jay, unfortunately I cannot seem to find the definition of "Html.EnumDropDownListFor" in my razor view. PS: I am using ASP.NET Core 1.0 Commented Oct 14, 2016 at 22:38

1 Answer 1

44

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
} 
Sign up to request clarification or add additional context in comments.

3 Comments

This is highly confusing since you're supposed to use [DisplayName(...)] for standard model properties. :/
@qJake System.ComponentModel.DisplayAttribute (for [Display]) replaces the older DisplayNameAttribute (for [DisplayName]) in .NET 4.0. See here: stackoverflow.com/questions/5243665/…
I think the important part was switching from [Description("Paid Monthly")] to [Display(Name="Paid Monthly")], not switching from a non-generic method to a generic version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.