例:
要求select下拉列表展示枚举中所有项
枚举类:
public enum AdverType
{
[Description("跨栏广告")]
HurdleAdverType = 0,
[Description("分栏广告")]
ColumnAdverType = 1,
}
控制器类:
public IActionResult AdvertModify(string Id)
{
ViewBag.modelAdverType = EnumHelper.GetEnumModel<AdverType>();
ViewBag.Id = Id;
return View();
}
页面调用:
image.png获得枚举的描述:
1.控制器
public IActionResult Index()
{
ViewBag.modelAdverType = EnumHelper.GetEnumModel<AdverType>();
ViewBag.modelAdverTypeJson = Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.modelAdverType);
return View();
}
js调用
var advertType = JSON.parse('@Html.Raw(ViewBag.modelAdverTypeJson)');
AdvertType.find(p => p.Value == advertType ).Description;
2.后台方法调用
public string GetEnumDes(string value)
{
var listenum = EnumHelper.GetEnumModel<AdverType>();
var des=listenum.Find(p => p.Value == value).Description;
return des;
}
枚举帮助类:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
namespace EnumHelpLL.Infrastructure.Utility
{
public class EnumHelper
{
/// <summary>
/// 用于保存枚举值Name,Value,Description的类
/// </summary>
public class EnumModel
{
public string Description { get; set; }
public string Name { get; set; }
public int Value { get; set; }
}
/// <summary>
/// 获取枚举的Name,Value,Description
/// </summary>
/// <typeparam name="T">枚举</typeparam>
/// <returns></returns>
public static List<EnumModel> GetEnumModel<T>()
{
List<EnumModel> listEnumModel = new List<EnumModel>();
#region
/*
* 表示类型声明,类类型,接口类型,数组类型,值类型,枚举类型,类型参数,泛型类型定义,以及开放或封闭构造的泛型。
*/
#endregion
Type type = typeof(T);
#region
/*
* FieldInfo http://msdn.microsoft.com/zh-cn/library/system.reflection.fieldinfo(v=vs.95).aspx
*
*/
#endregion
FieldInfo[] fieldInfos = type.GetFields();
foreach (FieldInfo fieldInfo in fieldInfos)
{
EnumModel enumModel = new EnumModel();
if (!fieldInfo.IsSpecialName)
{
enumModel.Name = fieldInfo.Name;
enumModel.Value = ((T)System.Enum.Parse(type, fieldInfo.Name)).GetHashCode();
DescriptionAttribute[] enumAttributeList = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (enumAttributeList != null && enumAttributeList.Length > 0)
{
enumModel.Description = enumAttributeList[0].Description;
}
else
{
enumModel.Description = fieldInfo.Name;
}
/*
* 下面的方法也可以获得枚举的描述
dynamic dy = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (dy != null && dy.Length>0)
{
enumModel.Description = dy[0].Description;
}
else
{
enumModel.Description = fieldInfo.Name;
}
*/
listEnumModel.Add(enumModel);
}
}
return listEnumModel;
}
}
}
网友评论