MVC4 enum and radio button list

后端 未结 5 1527
别跟我提以往
别跟我提以往 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:05

    I was able to combine some of the approaches from other answers with some added features:

    EnumRadioButtonList.cshtml

    @model Enum
    @foreach (var item in EnumHelper.GetSelectList(Model.GetType()))
    {
        
    }

    This uses EnumHelper.GetSelectList() as a sort of hack so that you can use display attributes with your enum members:

    public enum TestEnum
    {
        First,
        [Display(Name = "Second Member")]
        Second,
        Third
    }
    

    Usage:

    @Html.EditorFor(m => m.TestEnumProperty, "EnumRadioButtonList")
    

    Yields:

    Image

    I'm also using the Bootstrap radio button styles with a separate helper for the inline version:

    EnumRadioButtonListInline.cshtml

    @model Enum
    @foreach (var item in EnumHelper.GetSelectList(Model.GetType()))
    {
        
    }
    

提交回复
热议问题