【问题标题】:using StringValue for rendering enum properties [duplicate]使用 StringValue 呈现枚举属性 [重复]
【发布时间】:2016-12-20 06:34:53
【问题描述】:

在 razor 视图中,我正在使用这样的枚举值渲染组合框

@Html.DropDownListFor(m => m.CarType, new SelectList(Enum.GetValues(typeof(CarTypeEnum))), 
      "Select value", new { @class = "form-control" })

public enum CarTypeEnum
{
  [StringValue("Car type one")]
   CarTypeOne = 1,

  [StringValue("Car type two")]
   CarTypeTwo = 2,
}

如何使用 DropDownListFor 助手在组合框中呈现 StringValue,例如 Car type one 而不是 CarTypeOne

【问题讨论】:

标签: c# .net asp.net-mvc enums


【解决方案1】:

您可以使用 C# 中提供的 Display 属性。应该是这样的:

public enum CarTypeEnum
{
[Display(Name="Car type one")]
CarTypeOne = 1,
[Display(Name="Car type two")]
CarTypeTwo
}

您还只需为您的第一个枚举提供一个值。休息会自动生成。

我还有一个枚举扩展,可以将显示属性中提供的文本 als 文本放入您的下拉列表中:

public static class EnumExtensions
    {/// <summary>
     ///     A generic extension method that aids in reflecting 
     ///     and retrieving any attribute that is applied to an `Enum`.
     /// </summary>
        public static TAttribute GetAttribute<TAttribute>(this Enum enumValue)
                where TAttribute : Attribute
        {
            return enumValue.GetType()
                            .GetMember(enumValue.ToString())
                            .First()
                            .GetCustomAttribute<TAttribute>();
        }
    }

用法如下:

new SelectListItem
            {
                Text = CarTypeEnum.CarTypeOne.GetAttribute<DisplayAttribute>().Name
            }

【讨论】:

  • 这不能应用,因为 .First() 里面提供的 EnumExtensions 报告错误。您在此处发帖之前尝试过吗?
  • 是的,我在我的网络应用程序中使用它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 2014-11-18
  • 2014-08-18
相关资源
最近更新 更多