使用StringValue渲染枚举属性

时间:2016-12-20 06:34:54

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

在剃刀内部视图中,我使用这样的枚举值渲染组合框

@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

1 个答案:

答案 0 :(得分: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
            }