How do you add a description to you enum values in C# to use with a dropdown list in ASP.NET MVC?
本问题已经有最佳答案,请猛点这里访问。
如果要在ASP.NET MVC视图中使用下拉列表的枚举,以便可以将枚举值或枚举名称用作选择列表项值,并将更具描述性的文本用作选择列表项文本,我将如何执行此操作?
下面是一个如何做到这一点的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | 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"; } @Model.ExampleTitle @Html.LabelFor(model => model.ExampleEnum) @Html.EnumDropDownListFor(model => model.ExampleEnum) 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; } } } |