Asp.Net 之 枚举类型的下拉列表绑定
2024-08-20 08:53:21
有这样一个学科枚举类型:
/// 学科
/// </summary>
public enum Subject
{
None = ,
[Description("语文")]
Chinese = , [Description("数学")]
Mathematics = , [Description("英语")]
English = , [Description("政治")]
Politics = , [Description("物理")]
Physics = , [Description("化学")]
Chemistry = , [Description("历史")]
History = , [Description("地理")]
Geography = , [Description("生物")]
Biology =
}
这里使用了一个Description特性,目的是为了在一个DropDownList列表中绑定文本数据。
这里使用了一个扩展方法,目的为了返回一个Value和Text的数据列表,上方法:
/// 枚举辅助类
/// </summary>
public static class EnumHelper
{
/// <summary>
/// 获得枚举类型数据项(不包括空项)
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns></returns>
public static IList<object> GetItems(this Type enumType)
{
if (!enumType.IsEnum)
throw new InvalidOperationException(); IList<object> list = new List<object>(); // 获取Description特性
Type typeDescription = typeof(DescriptionAttribute);
// 获取枚举字段
FieldInfo[] fields = enumType.GetFields();
foreach (FieldInfo field in fields)
{
if (!field.FieldType.IsEnum)
continue; // 获取枚举值
int value = (int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null); // 不包括空项
if (value > )
{
string text = string.Empty;
object[] array = field.GetCustomAttributes(typeDescription, false); if (array.Length > ) text = ((DescriptionAttribute)array[]).Description;
else text = field.Name; //没有描述,直接取值 //添加到列表
list.Add(new { Value = value, Text = text });
}
}
return list;
}
}
这里采用特性反射的方式得到了对应的Value和Text,最后返回了一个new { Value = …, Text = … }的匿名类的列表。
那么页面上实现就相当简单了:
ddlSubject.DataSource = typeof(Subject).GetItems();
ddlSubject.DataTextField = "Text";
ddlSubject.DataValueField = "Value";
ddlSubject.DataBind();
最新文章
- scrapy爬虫笔记(二)------交互式爬取
- LightOJ1283 Shelving Books(DP)
- Event --mysql的scheduler.md
- OpenCV - Operations on Arrays 对数组(矩阵)的一些操作
- 06链队列_LinkQueue--(栈与队列)
- Ubuntu下将vim配置为Python IDE(转)
- UC高级编程--实现myls程序
- 使用newtonsoft序列化
- POJ2387 Til the Cows Come Home 【Dijkstra】
- SpringIOC和AOP原理 设计模式
- lambda Helper
- vue-router-1-安装与基本使用
- monkey配置及简单报告生成(安卓)
- 关于pthread_cond_wait()使用的理解
- spark 调优——基础篇
- Excel 中 VLOOKUP() 函数小结
- go语言基础之二维数组
- ios开发遇到的问题
- 《java虚拟机》----虚拟机字节码执行引擎
- 百度编辑器(ueditor)@功能之获取坐标