【问题标题】:Trying to work with @Html.CheckBox for to display text of enum尝试使用 @Html.CheckBox 来显示枚举文本
【发布时间】:2013-08-24 04:23:09
【问题描述】:

我开始这样做是为了在我的视图中显示一些复选框:

@Html.LabelFor(m => m.MyEnum, T("Pick Your Poison"))
<div>                
    @for(int i = 0; i < Model.Alcohol.Count; i++)
    {
        <label>
            @T(Model.Alcohol[i].Text)
            @Html.CheckBoxFor(m => Model.Alcohol[i].Selected)
            @Html.HiddenFor(m => Model.Alcohol[i].Value)
        </label>
    }
</div>

请注意:这里重要的是@T 方法,它用于处理将文本翻译成其他语言。

这行得通。我有一个简单的enum,后端有一些方法可以将其转换为视图中的文本。所以,enum 如:

public enum MyEnum
{
    Beer = 1,
    Vodka = 2,
    Rum = 3
}

将显示带有这 3 个选项的复选框列表。在我的 ViewModel 中,我这样做:

Alcohol= Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(x =>
{
    return new SelectListItem { 
        Text = x.ToString().ToUpper(), Value = ((int)x).ToString()
        };
    }).ToList();
}

但是,我希望复选框附带更多描述性文字。我宁愿enum 有这种或类似类型的系统(我将解释下划线):

public enum MyEnum
{
    I_like_Beer = 1,
    I_hate_Vodka = 2,
    Meh__Rum = 3
}

我试图创建一种方法来去除 下划线 并将其替换为空格,在 双下划线 的情况下将其替换为逗号,所以当复选框显示时,它们看起来像:

我喜欢啤酒

我讨厌伏特加

嗯,朗姆酒

但我不知道该怎么做。另外,我不确定这是否是最好的选择。我很想保留@T 函数,因为这样我就可以轻松地在我的应用程序中翻译内容。否则,做任何其他事情都会对我造成伤害。

我可能应该做什么的任何例子?谢谢。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 enums


    【解决方案1】:

    我喜欢在这类事情上使用数据注释。这可以防止疯狂地尝试找出可变可读的文本约定。

    public enum MyEnum
    {
        [Description("I like beer")]
        Beer = 1,
        [Description("I hate vodka")]
        Vodka = 2,
        [Description("Meh, rum")]
        Rum = 3
    };
    

    您可以在运行时使用reflection 访问该值:

    MyEnum sampleEnum = MyEnum.Beer;
    var attr = typeof(MyEnum)
        .GetMember(sampleEnum.ToString())
        .First()
        .GetCustomAttributes(typeof(DescriptionAttribute), false)
        .First() as DescriptionAttribute;
    string description = attr.Description;
    

    当然,这有点冗长(并且仍然需要错误处理),但是您可以创建一个扩展方法来简化使用语法:

    public static string GetDescriptionOrDefault<T>(this T enumValue, string defaultValue = null)
    {
        var attr = typeof(T)
            .GetMember(enumValue.ToString())
            .First()
            .GetCustomAttributes(typeof(DescriptionAttribute), false)
            .FirstOrDefault() as DescriptionAttribute;
        return attr == null ? (defaultValue ?? enumValue.ToString()) : attr.Description;
    }
    

    这将允许视图简单地编写:

    MyEnum sampleEnum = MyEnum.Beer;
    string description = sampleEnum.GetDescriptionOrDefault();
    

    【讨论】:

    • 我会将最后一段代码放在控制器中的什么位置?另外,它适合我的@T 构造吗?
    • @REMESQ 是的,x 在您的示例中是枚举值,对吧?所以它会是x.GetDescription() 或其他。它应该与 T 结构一起使用,因为 T 只接受一个字符串参数:T(x.GetDescription()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多