Search code examples
c#enumsradio-buttondata-annotationshtml-helper

Radio Button For Enum (DataAnnotation)


I have this enum:

[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

I put this EnumDropDownList in my view:

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

It's perfect, showing the name I put in DataAnnotation.. BUT when I try to use this Enum as RadioButton, it doesn't show the name in Display(Name...), show the name of the attribute..

Here's my RadioButton:

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

I've already tested Enum.GetNames (without @value.ToString(), just @value)..

Can someone help me?

Btw, I want it as a Radio Button, because it has a fixed number of elements and has only a few options, so I prefer to use Radio Button.


Solution

  • Unfortunately there is no out-of-the-box control for this like you get with @Html.EnumDropDownListFor. You can, however, create an editor template for radio button enums like mentioned in the following: MVC5: Enum radio button with label as displayname (see selected answer).