Html.GetEnumSelectList - Getting Enum values with spaces

房东的猫 提交于 2019-12-22 04:07:14

问题


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
} 

回答1:


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
} 


来源:https://stackoverflow.com/questions/40052794/html-getenumselectlist-getting-enum-values-with-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!