【问题标题】:How do you add a description to you enum values in C# to use with a dropdown list in ASP.NET MVC? [duplicate]如何在 C# 中为枚举值添加描述以与 ASP.NET MVC 中的下拉列表一起使用? [复制]
【发布时间】:2015-03-25 00:43:33
【问题描述】:

如果我想在我的 ASP.NET MVC 视图中将我的枚举用于下拉列表,以便我可以将枚举值或枚举名称作为选择列表项值,并将更具描述性的文本作为选择列表项文本我该怎么做?

【问题讨论】:

  • 另见stackoverflow.com/a/8825668/298053。尽管我们感谢您的主动性,但请务必在发布 QA 之前进行搜索。问题/答案相隔 1 分钟,很明显您只是为了参考 - 只需确保它是新的。
  • 如果您想推广该代码,请随时添加链接问题的答案。问题是一样的,答案也是一样的。
  • 我看到了其他帖子。我错过了我的搜索。我的帖子干净多了,不需要阅读一堆帖子和链接。添加到其他帖子只会增加问题。
  • 对于 MVC 5,重复中提到的 [Display] 属性,this answer from it 与您的基本相同 - 代码更少,插图更多。我不认为添加新的问答有助于人们更好地找到结果。
  • 是的,[Display] 属性非常酷。不幸的是,我们现在使用的是 MVC 4。

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


【解决方案1】:

这是一个如何做到这一点的示例:

public enum ExampleEnum
{
    [ComponentModel.Description("Example One")]
    ExampleOne,
    [ComponentModel.Description("Example Two")]
    ExampleTwo,
    [ComponentModel.Description("Example Three")]
    ExampleThree,
    [ComponentModel.Description("Example Four")]
    ExampleFour,
    ExampleWithNoDescription
}

@using Mvc4Scratch.Web.Helpers
@model Mvc4Scratch.Web.ViewModels.EnumExampleViewModel

@{
    ViewBag.Title = "EnumDropDownExample";
}

<h2>@Model.ExampleTitle</h2>

<div>
    @Html.LabelFor(model => model.ExampleEnum)
    @Html.EnumDropDownListFor(model => model.ExampleEnum)
</div>

using Mvc4Scratch.Web.Helpers;

namespace Mvc4Scratch.Web.ViewModels
{
    public class EnumExampleViewModel
    {
        public string ExampleTitle { get; set; }

        public ExampleEnum ExampleEnum { get; set; }
    }
}

using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Mvc4Scratch.Web.Helpers
{
    public static class Extensions
    {
        public static string GetName(this Enum value)
        {
            return Enum.GetName(value.GetType(), value);
        }

        public static string GetDescription(this Enum value)
        {
            var fieldInfo = value.GetType().GetField(value.GetName());
            var descriptionAttribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
            return descriptionAttribute == null ? value.GetName() : descriptionAttribute.Description;
        }

        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> enumAccessor)
        {
            var propertyInfo = enumAccessor.ToPropertyInfo();
            var enumType = propertyInfo.PropertyType;
            var enumValues = Enum.GetValues(enumType).Cast<Enum>();
            var selectItems = enumValues.Select(s => new SelectListItem
                                                     {
                                                         Text = s.GetDescription(),
                                                         Value = s.ToString()
                                                     });

            return htmlHelper.DropDownListFor(enumAccessor, selectItems);
        }

        public static PropertyInfo ToPropertyInfo(this LambdaExpression expression)
        {
            var memberExpression = expression.Body as MemberExpression;
            return (memberExpression == null) ? null : memberExpression.Member as PropertyInfo;
        }
    }
}

【讨论】:

  • 当您不想涉及数据库表或更大的类时,我认为这是一种非常干净的方法。它还展示了扩展方法是多么有用的案例。
  • 顺便说一句,请查看 Elton Stoneman 在 Pluralsight 上的 C# 扩展方法课程。好东西,你可以看到它的实际效果!
  • 这确实是阅读扩展方法的有趣来源。
猜你喜欢
  • 1970-01-01
  • 2012-05-17
  • 2016-08-22
  • 2013-08-26
  • 1970-01-01
  • 2011-02-08
  • 2010-09-28
相关资源
最近更新 更多