MVC4 enum and radio button list

后端 未结 5 1548
别跟我提以往
别跟我提以往 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条回答
  •  猫巷女王i
    2020-11-30 02:17

    I suggest a similar approach to the other answers, but with the following editor template; EnumRadioButtonList.cshtml, in the Views\Shared\EditorTemplates directory:

    @model Enum
    @foreach (var value in Enum.GetValues(Model.GetType()))
    {
        var id = TagBuilder.CreateSanitizedId(string.Format(
            "{0}_{1}_{2}", ViewData.TemplateInfo.HtmlFieldPrefix, Model.GetType(), value));
        
    @Html.RadioButton(string.Empty, value, value.Equals(Model), new { id }) @Html.Label(value.ToString(), new { @for = id })
    }

    The HTML id of each radio button needs to be unique. Therefore the above code prefixes the id with the bound property's name by means of using ViewData.TemplateInfo.HtmlFieldPrefix. This ensures unique ids if the model contained multiple properties that used this enum, and if this editor template was used for each of them.

    The accompanying label for each radio button will have its for attribute correctly set. This means that the user can select a radio button by clicking the label text, a much bigger and better click target than just the radio button itself.

    For MVC model binding, the radio buttons will all have their HTML name property value set to that of the property that was specified in the EditorFor call (Airline in this scenario).

    To use it:

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

提交回复
热议问题