raj*_*azo 21 c# asp.net asp.net-mvc enums razor
如何在Razor的下拉列表中显示我的枚举的自定义名称?我目前的代码是:
@Html.DropDownListFor(model => model.ExpiryStage,
new SelectList(Enum.GetValues(typeof(ExpiryStages))),
new { @class = "selectpicker" })
Run Code Online (Sandbox Code Playgroud)
我的枚举是:
public enum ExpiryStages
{
[Display(Name = "None")]
None = 0,
[Display(Name = "Expires on")]
ExpiresOn = 1,
[Display(Name = "Expires between")]
ExpiresBetween = 2,
[Display(Name = "Expires after")]
ExpiresAfter = 3,
[Display(Name = "Current")]
Current = 4,
[Display(Name = "Expired not yet replaced")]
ExpiredNotYetReplaced = 5,
[Display(Name = "Replaced")]
Replaced = 6
}
Run Code Online (Sandbox Code Playgroud)
例如,我想在DropDownList中显示"Expired not yet changed"而不是ExpiredNotYetReplaced.
Muh*_*bal 39
从MVC 5.1开始,他们添加了这个新助手.你只需要一个枚举
public enum WelcomeMessageType
{
[Display(Name = "Prior to accepting Quote")]
PriorToAcceptingQuote,
[Display(Name = "After Accepting Quote")]
AfterAcceptingQuote
}
Run Code Online (Sandbox Code Playgroud)
您可以通过编写创建显示名称的下拉列表
@Html.EnumDropDownListFor(model => model.WelcomeMessageType, null, new { @id = "ddlMessageType", @class = "form-control", @style = "width:200px;" })
Run Code Online (Sandbox Code Playgroud)
我有一个枚举扩展名来检索显示名称。
public static string GetDescription<TEnum>(this TEnum value)
{
var attributes = value.GetAttributes<DescriptionAttribute>();
if (attributes.Length == 0)
{
return Enum.GetName(typeof(TEnum), value);
}
return attributes[0].Description;
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用:
Enum.GetValues(typeof(ExpiryStages)).Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
Run Code Online (Sandbox Code Playgroud)
我使用一个方便的助手从枚举中生成选择列表:
public static SelectList SelectListFor<T>()
where T : struct
{
var t = typeof (T);
if(!t.IsEnum)
{
return null;
}
var values = Enum.GetValues(typeof(T)).Cast<T>()
.Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
return new SelectList(values, "Id", "Name");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18659 次 |
| 最近记录: |