MVC4 enum and radio button list

后端 未结 5 1535
别跟我提以往
别跟我提以往 2020-11-30 02:02

I have seen a few threads on this but none seem to apply to MVC4 because the RadioButtonFor html extension method/helper does not exist.

Say I have an enum list - i.

5条回答
  •  借酒劲吻你
    2020-11-30 02:24

    I improved the highest rated answer by asymptoticfault a bit to reflect selected values too. Save this as EnumRadioButton.cshtml to your shared views EditorTemplates folder:

    @model Enum
    @foreach (var value in Enum.GetValues(Model.GetType()))
    {
        if (Equals(Model, value))
        {
            @Html.RadioButtonFor(m => m, value, new {@checked = "checked"})
        }
        else
        {
            @Html.RadioButtonFor(m => m, value)
        }
    
        @Html.Label(value.ToString())
    }
    

    Usage:

    @Html.EditorFor(item => Model.MyEnumType, "EnumRadioButton")
    

提交回复
热议问题