栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何通过MVC剃刀代码获取Enum成员的显示名称属性?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何通过MVC剃刀代码获取Enum成员的显示名称属性?

更新

第一个解决方案着重于从枚举中获取显示名称。下面的代码应该是您的问题的确切解决方案。

您可以将此帮助程序类用于枚举:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Reflection;public static class EnumHelper<T>{    public static IList<T> GetValues(Enum value)    {        var enumValues = new List<T>();        foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))        { enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));        }        return enumValues;    }    public static T Parse(string value)    {        return (T)Enum.Parse(typeof(T), value, true);    }    public static IList<string> GetNames(Enum value)    {        return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();    }    public static IList<string> GetDisplayValues(Enum value)    {        return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();    }    private static string lookupResource(Type resourceManagerProvider, string resourceKey)    {        foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))        { if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager)) {     System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);     return resourceManager.GetString(resourceKey); }        }        return resourceKey; // Fallback with the key name    }    public static string GetDisplayValue(T value)    {        var fieldInfo = value.GetType().GetField(value.ToString());        var descriptionAttributes = fieldInfo.GetCustomAttributes( typeof(DisplayAttribute), false) as DisplayAttribute[];        if (descriptionAttributes[0].ResourceType != null) return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);        if (descriptionAttributes == null) return string.Empty;        return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();    }}

然后可以在视图中使用它,如下所示:

<ul>    @foreach (var value in @EnumHelper<UserPromotion>.GetValues(UserPromotion.None))    {         if (value == Model.JobSeeker.Promotion)        { var description = EnumHelper<UserPromotion>.GetDisplayValue(value); <li>@Html.DisplayFor(e => description )</li>        }    }</ul>

希望能帮助到你!:)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/597026.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号