C# 如何向C中的枚举值添加说明,以便与ASP.NET MVC中的下拉列表一起使用?

C# 如何向C中的枚举值添加说明,以便与ASP.NET MVC中的下拉列表一起使用?,c#,asp.net-mvc-4,enums,extension-methods,C#,Asp.net Mvc 4,Enums,Extension Methods,如果我想在ASP.NET MVC视图中使用我的枚举作为下拉列表,这样我就可以将枚举值或枚举名称作为选择列表项的值,并将更具描述性的文本作为选择列表项的文本,我将如何执行此操作?下面是一个如何执行此操作的示例: public enum ExampleEnum { [ComponentModel.Description("Example One")] ExampleOne, [ComponentModel.Description("Example Two")] Exa

如果我想在ASP.NET MVC视图中使用我的枚举作为下拉列表,这样我就可以将枚举值或枚举名称作为选择列表项的值,并将更具描述性的文本作为选择列表项的文本,我将如何执行此操作?

下面是一个如何执行此操作的示例:

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;
        }
    }
}
公共枚举示例枚举
{
[组件模型说明(“示例一”)]
例如,,
[组件模型说明(“示例二”)]
例二,,
[组件模型说明(“示例三”)]
例三,,
[组件模型说明(“示例四”)]
例四,,
带有节点描述的示例
}
@使用Mvc4Scratch.Web.Helpers
@模型Mvc4Scratch.Web.ViewModels.EnumExampleViewModel
@{
ViewBag.Title=“EnumDropDownExample”;
}
@Model.ExampleTitle
@LabelFor(model=>model.ExampleEnum)
@EnumDropDownListFor(model=>model.ExampleEnum)
使用Mvc4Scratch.Web.Helpers;
命名空间Mvc4Scratch.Web.ViewModels
{
公共类EnumExampleViewModel
{
公共字符串示例Title{get;set;}
公共示例枚举示例枚举{get;set;}
}
}
使用制度;
使用系统组件模型;
使用System.Linq;
使用System.Linq.Expressions;
运用系统反思;
使用System.Web.Mvc;
使用System.Web.Mvc.Html;
命名空间Mvc4Scratch.Web.Helpers
{
公共静态类扩展
{
公共静态字符串GetName(此枚举值)
{
返回Enum.GetName(value.GetType(),value);
}
公共静态字符串GetDescription(此枚举值)
{
var fieldInfo=value.GetType().GetField(value.GetName());
var descriptionAttribute=fieldInfo.GetCustomAttributes(typeof(descriptionAttribute),false);
return descriptionAttribute==null?value.GetName():descriptionAttribute.Description;
}
公共静态MvcHtmlString EnumDropDownListFor(此HtmlHelper HtmlHelper,表达式枚举访问器)
{
var propertyInfo=enumAccessor.ToPropertyInfo();
var enumType=propertyInfo.PropertyType;
var enumValues=Enum.GetValues(enumType.Cast();
var selectItems=enumValues.Select(s=>newselectListItem
{
Text=s.GetDescription(),
Value=s.ToString()
});
返回htmlHelper.DropDownListFor(enumAccessor,selectItems);
}
public static PropertyInfo ToPropertyInfo(此LambdaExpression表达式)
{
var memberExpression=expression.Body作为memberExpression;
返回(memberExpression==null)?null:memberExpression.Member as PropertyInfo;
}
}
}

我认为,当您不想涉及db表或更大的类时,这是一种非常干净的方法。它还展示了扩展方法的实用性。顺便说一句,请查看Elton Stoneman在Pluralsight上开设的C#extension methods课程。好东西,你可以在行动中看到这一点!阅读扩展方法确实是一个有趣的来源。虽然我们感谢您的主动,但请确保在发布QA之前进行搜索。问题/答案相隔1分钟,很明显你只是想作为一个参考——只要确保它是一个新的。如果你想推广该代码,请随意添加链接问题的答案。问题是一样的,答案也是一样的。我看到了其他的帖子。我通过搜索错过了。我的帖子非常干净,不需要阅读大量的帖子和链接。添加到其他帖子只会增加问题。对于MVC 5,在副本中提到了
[Display]
属性,基本上与您的相同-代码更少,说明更多。我不认为添加新的Q&a有助于人们更好地找到结果。是的,[Display]属性非常酷。不幸的是,到目前为止,我们还在MVC4上。