枚举中的单选按钮组 [英] 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.
虚拟机看起来像这样
public class OptionViewModel<TEnum> where TEnum : struct, IConvertible
{
public TEnum SelectedValue { get; set; }
}
然后,我可以通过编写
public enum Numbers { One, Two, Three }
...
NumberOptions = new OptionViewModel<Numbers>();
...
,然后通过
@model OptionViewModel<TEnum>
@foreach (var value in Enum.GetValues(typeof(TEnum)).Cast<TEnum>())
{
var selected = value == Model.SelectedValue;
@Html.RadioButton(value.ToString(), value, selected)
}
不幸的是,模板甚至没有编译,因为没有类型'TEnum'。
Unfortunately, the template doesn't even compile, because there is no type 'TEnum', of course.
有没有更好的方法(工作)的方法吗?我真的会达到这种抽象水平,因为枚举中的单选按钮组在我的项目中是很常见的情况,并且带有附加属性,例如IsVisible,IsEnabled等。
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;
}
}
在控制器中:
NumberOptions = OptionViewModel.create<Numbers>();
在视图中,如果我没记错的话,mvc表单将返回Model.SelectedValue中的值:
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)
}
这篇关于枚举中的单选按钮组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!