在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
发布于 2016-12-20 06:43:21
您可以使用C#中提供的显示属性。大概是这样的:
public enum CarTypeEnum
{
[Display(Name="Car type one")]
CarTypeOne = 1,
[Display(Name="Car type two")]
CarTypeTwo
}
你也只需要给你的第一个枚举提供一个值。Rest将自动生成。
我还有一个枚举扩展,可以将显示属性als text中提供的文本放入下拉列表中:
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
}
https://stackoverflow.com/questions/41236223
复制