简体   繁体   English

枚举中的单选按钮组

[英]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. 不幸的是,模板甚至没有编译,因为当然没有类型“ TEnum”。

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. 我真的会达到这种抽象水平,因为枚举中的单选按钮组在我的项目中是很常见的情况,并且带有附加属性,例如IsVisible,IsEnabled等。

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: 在视图中,如果我没记错的话,MVC表单将返回Model.SelectedValue中的值:

@model OptionViewModel

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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