【问题标题】:Html.GetEnumSelectList - Getting Enum values with spacesHtml.GetEnumSelectList - 获取带空格的枚举值
【发布时间】:2017-02-24 10:54:17
【问题描述】:

我在我的 Razor 视图中使用带有选择标记的 asp-items="@Html.GetEnumSelectList(typeof(Salary))",以根据 enum Salary 填充列表值。

但是,我的枚举包含一些我想在其中包含空格的项目。例如。其中一项是PaidMonthly,但是当我使用Html.GetEnumSelectList 显示它时,我希望它显示为"Paid Monthly"(其中有一个空格)

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

谁能帮我解决这个问题?

(我的代码示例)-> 使用 ASP.NET Core 1.0

剃刀视图:

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

枚举工资:

public enum Salary
{
    [Description("Paid Monthly")]
    PaidMonthly = 1,
    PaidYearly = 2
} 

【问题讨论】:

  • 显示你尝试过的代码
  • 试试[Display(Name = "Paid Monthly")]
  • 其实我也试过了。虽然不起作用:\
  • 试试斯蒂芬所说的然后使用@Html.EnumDropDownListFor(model =&gt; model.Salary),假设你的列表是一个下拉列表...
  • 嗨,Jay,不幸的是,我似乎无法在我的 razor 视图中找到“Html.EnumDropDownListFor”的定义。 PS:我使用的是 ASP.NET Core 1.0

标签: c# html razor enums asp.net-core-mvc


【解决方案1】:

我设法解决了。我只需要使用GetEnumSelectList&lt;&gt; 的另一种方法,在Razor 视图中我们需要使用Display 属性。

代码如下:

剃刀视图:

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

枚举工资:

public enum Salary
{
    [Display(Name="Paid Monthly")]
    PaidMonthly = 1,
    PaidYearly = 2
} 

【讨论】:

  • 这非常令人困惑,因为您应该将[DisplayName(...)] 用于标准模型属性。 :/
  • @qJake System.ComponentModel.DisplayAttribute(对于[Display])在.NET 4.0 中替换了旧的DisplayNameAttribute(对于[DisplayName])。见这里:stackoverflow.com/questions/5243665/…
  • 我认为重要的部分是从[Description("Paid Monthly")] 切换到[Display(Name="Paid Monthly")],而不是从非泛型方法切换到泛型版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2022-10-08
相关资源
最近更新 更多