简体   繁体   中英

Radio button group from enum

I'm trying to come up with a generic view model and editor template for enum types in a way that possible values are rendered into a radio button group. Let me elaborate.

The VM looks like so

public class OptionViewModel<TEnum> where TEnum : struct, IConvertible
{
   public TEnum SelectedValue { get; set; }
}

I could then create an instance for any enum in my project by writing

public enum Numbers { One, Two, Three }

...
NumberOptions = new OptionViewModel<Numbers>();
...

and then have that rendered via

@model OptionViewModel<TEnum>

@foreach (var value in Enum.GetValues(typeof(TEnum)).Cast<TEnum>())
{
   var selected = value == Model.SelectedValue;

   @Html.RadioButton(value.ToString(), value, selected)
}

Unfortunately, the template doesn't even compile, because there is no type 'TEnum', of course.

Is there a better (working) way to do this? I'd really get this level of abstraction, as radio button groups from enums is a fairly common case in my project, and it comes with additional attributes, such as IsVisible, IsEnabled and the like.

I would store the enum values in your view model as strings and create a function that accepts the generic parameters to create the view model.

public class OptionViewModel
{
   public string SelectedValue { get; set; }
   public List<string> Values { get; set; }

   public static OptionViewModel Create<TEnum>() where TEnum : struct, IConvertible
   {
        var ovm = new OptionViewModel();
        foreach (var value in Enum.GetValues(typeof(TEnum)).Cast<TEnum>())
        {
             ovm.Values.Add(value);
        }
        return ovm;
   }
}

In the controller:

NumberOptions = OptionViewModel.create<Numbers>();

In the view, and if i'm not mistaken mvc forms will return the value in Model.SelectedValue:

@model OptionViewModel

@foreach (var value in model.Values)
{
   var selected = value == Model.SelectedValue;

   @Html.RadioButton(Model.SelectedValue, value, selected)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM