如何本地化枚举并使用类似于 Html.SelectListFor的内容

发布于 2024-10-08 02:31:38 字数 754 浏览 0 评论 0原文

假设我得到了以下类和枚举:

public class MyModel
{
    [DisplayName("Min egenskap")]
    public MyEnum TheProperty {get;set;}
}

public enum MyEnum
{
  [DisplayName("Inga från Sverige")]
  OneValue,

  [DisplayName("Ett annat värde")]
  AnotherValue
}

上面的代码不起作用,因为 DisplayNameAttribute 不能在枚举上使用。还有其他属性可以使用吗?

我想做的是使用 Html.SelectListFor(m => m.TheProperty) 之类的东西生成一个漂亮的 html select 标签。该列表将在生成过程中使用 DisplayNameAttribute 或类似属性。

想要的结果:

<select name="TheProperty">
<option value="OneValue">Inga från Sverige</option>
<option value="AnotherValue" selected="selected">Ett annat värde</option>
</select>

Let's say that I got the following class and enum:

public class MyModel
{
    [DisplayName("Min egenskap")]
    public MyEnum TheProperty {get;set;}
}

public enum MyEnum
{
  [DisplayName("Inga från Sverige")]
  OneValue,

  [DisplayName("Ett annat värde")]
  AnotherValue
}

The above code doesn't work since DisplayNameAttribute cannot be used on enums. Are there another attribute that can be used?

What I want to do is to generate a nice html select tag using something like Html.SelectListFor(m => m.TheProperty). The list would use the DisplayNameAttribute or similar attribute during generation.

Wanted result:

<select name="TheProperty">
<option value="OneValue">Inga från Sverige</option>
<option value="AnotherValue" selected="selected">Ett annat värde</option>
</select>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

§普罗旺斯的薰衣草 2024-10-15 02:31:38

如何执行此操作的一个示例是在枚举上使用 [Description] 属性:

public enum DaysOfWeek
{
    [Description("Monday")]
    Monday = 1,

    [Description("Tuesday")]
    Tuesday = 2
}

然后创建此 EnumerationHelper 类,该类将允许您获取枚举的 Description 属性:

public static class EnumerationHelper
{
    //Transforms an enumeration description into a string 
    public static string Description<TEnum>(this TEnum enumObject)
    {
        Type type = enumObject.GetType();
        MemberInfo[] memInfo = type.GetMember(enumObject.ToString());

        if(memInfo != null && memInfo.Length > 0)
        {
            DescriptionAttribute[] attributes = (DescriptionAttribute[])memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
        }

        return enumObject.ToString();

    }
}

然后您可以查询枚举类以获取值和描述然后构建一个 SelectList。您必须在此类中引用 EnumerationHelper:

var listOfDaysOfWeek = (from DaysOfWeek d in Enum.GetValues(typeof(DaysOfWeek))
                        select new { ID = d, Description = d.Description() });

viewModel.selectListDaysOfWeek = new SelectList(listOfDaysOfWeek, "ID", "Description");

最后在您看来:

<%: Html.DropDownListFor(m => m.DayOfWeek, Model.DaysOfWeek) %>

我希望这会有所帮助。

An example of how to do this is to use the [Description] attribute on your enum:

public enum DaysOfWeek
{
    [Description("Monday")]
    Monday = 1,

    [Description("Tuesday")]
    Tuesday = 2
}

Then create this EnumerationHelper class that will allow you to get the Description attribute of your enum:

public static class EnumerationHelper
{
    //Transforms an enumeration description into a string 
    public static string Description<TEnum>(this TEnum enumObject)
    {
        Type type = enumObject.GetType();
        MemberInfo[] memInfo = type.GetMember(enumObject.ToString());

        if(memInfo != null && memInfo.Length > 0)
        {
            DescriptionAttribute[] attributes = (DescriptionAttribute[])memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
        }

        return enumObject.ToString();

    }
}

Then you can query your enum class to get the value and description to then build a SelectList. You must reference the EnumerationHelper in this class:

var listOfDaysOfWeek = (from DaysOfWeek d in Enum.GetValues(typeof(DaysOfWeek))
                        select new { ID = d, Description = d.Description() });

viewModel.selectListDaysOfWeek = new SelectList(listOfDaysOfWeek, "ID", "Description");

And then finally in your view:

<%: Html.DropDownListFor(m => m.DayOfWeek, Model.DaysOfWeek) %>

I hope this helps.

旧瑾黎汐 2024-10-15 02:31:38

我想在视图中显示枚举,所以我制作了一个类似的 Html 帮助器:

    /// <summary>
    /// Returns the [Description] value of a Enum member.
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    /// <typeparam name="TResult"></typeparam>
    /// <param name="helper"></param>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static MvcHtmlString DisplayEnumFor<TModel, TResult>(this HtmlHelper<TModel> helper, 
        Expression<Func<TModel, TResult>> expression) where TResult : struct {
        TResult value = expression.Compile().Invoke(helper.ViewData.Model);
        string propName = ExpressionHelper.GetExpressionText(expression);

        var description = typeof(TResult).GetMember(value.ToString())[0]
            .GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
        if (description != null) {
            return MvcHtmlString.Create((description as DescriptionAttribute).Description);
        }

        return MvcHtmlString.Create(value.ToString());
    }

用法:

@Html.DisplayEnumFor(m => m.SomeEnumProperty)

I wanted to display the Enum in the view so I made a similar Html helper:

    /// <summary>
    /// Returns the [Description] value of a Enum member.
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    /// <typeparam name="TResult"></typeparam>
    /// <param name="helper"></param>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static MvcHtmlString DisplayEnumFor<TModel, TResult>(this HtmlHelper<TModel> helper, 
        Expression<Func<TModel, TResult>> expression) where TResult : struct {
        TResult value = expression.Compile().Invoke(helper.ViewData.Model);
        string propName = ExpressionHelper.GetExpressionText(expression);

        var description = typeof(TResult).GetMember(value.ToString())[0]
            .GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
        if (description != null) {
            return MvcHtmlString.Create((description as DescriptionAttribute).Description);
        }

        return MvcHtmlString.Create(value.ToString());
    }

Usage:

@Html.DisplayEnumFor(m => m.SomeEnumProperty)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文