【问题标题】:Radio Button For Enum (DataAnnotation)枚举的单选按钮(DataAnnotation)
【发布时间】:2015-08-07 12:25:25
【问题描述】:

我有这个枚举:

[Display(Name = "Primary incomplete")]
PrimaryIncomplete = 1,

[Display(Name = "Primary")]
Primary = 2,

[Display(Name = "Secondary incomplete")]
SecondaryIncomplete = 3,

[Display(Name = "Secondary")]
Secondary = 4,

[Display(Name = "Higher education incomplete")]
HigherEducationIncomplete = 5,

[Display(Name = "Higher education")]
HigherEducation = 6,

[Display(Name = "Post-Graduation/MBA")]
PostGraduationMBA = 7

我把这个 EnumDropDownList 放在我的视图中:

@Html.EnumDropDownListFor(model => model.Scholarity, htmlAttributes: new { @class = "form-control" })

完美,显示了我在 DataAnnotation 中输入的名称。但是当我尝试将此 Enum 用作 RadioButton 时,它没有在 Display(Name...) 中显示名称,而是显示属性的名称。

这是我的 RadioButton:

@foreach (var value in Enum.GetValues(typeof(BlaBla.Models.Scholarity)))
{
    @Html.RadioButtonFor(model => model.Scholarity, value)
    <span>@value.ToString()</span> <br />
}

我已经测试过 Enum.GetNames(没有 @value.ToString(),只有 @value)..

有人可以帮我吗?

顺便说一句,我想要它作为单选按钮,因为它有固定数量的元素并且只有几个选项,所以我更喜欢使用单选按钮。

【问题讨论】:

    标签: c# enums radio-button data-annotations html-helper


    【解决方案1】:

    不幸的是,没有像 @Html.EnumDropDownListFor 这样的开箱即用控件。但是,您可以为单选按钮枚举创建一个编辑器模板,如下所述:MVC5: Enum radio button with label as displayname(请参阅所选答案)。

    【讨论】:

    • 好吧,工作量太大了,无论如何,谢谢.. 我更喜欢@Html.EnumDropDownListFor 然后,只有1行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2013-07-16
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 2014-10-14
    相关资源
    最近更新 更多