Enum Convert to DropDownList

public static List<DropDownItemViewModel> GetDropDownList<T>()
{
		List<DropDownItemViewModel> models = new List<DropDownItemViewModel>();
		Type type = typeof(T);
		foreach (int a in Enum.GetValues(typeof(T)))
		{
				DropDownItemViewModel model = new DropDownItemViewModel();
				model.Id = a;
				string name = Enum.GetName(type, a);
				FieldInfo field = type.GetField(name);
				DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
				if (attr != null)
				{
						model.Name = attr.Description;
				}
				models.Add(model);
		}
		return models;
}


public static Dictionary<string,string> GetEnumDropDownList(Type type)
{
		var model = new Dictionary<string, string>();
		foreach (int a in Enum.GetValues(type))
		{
				string name = Enum.GetName(type, a);
				FieldInfo field = type.GetField(name);
				DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
				model.Add( attr.Description, name);
		}
		return model;
}

作者:spike

分类: Net

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1