随笔 - 165, 文章 - 0, 评论 - 18, 阅读 - 22万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

ASP.NET MVC 枚举类型转LIST CONTROL控件

Posted on   火冰·瓶  阅读(360)  评论(0编辑  收藏  举报

在实际应用中,我们经常会用到下拉框、多选、单选等类似的控件,我们可以统称他们为List Control,他们可以说都是一种类型的控件,相同之处都是由一个或一组键值对的形式的数据进行绑定渲染而成的。

这些List Control的数据来源通常为数据库,固定值,但是有时候我们也会把数据写入在枚举或配置文件中,这篇文章针对数据写入枚举的情况下,如何在ASP.NET MVC中将枚举类型的数据读取并渲染成为List Control控件(下拉框、多选、单选等)

方法其实有很多种,但是疏通同归,基本都是先加载枚举类型,随后将枚举类型的数据转为字典类型或者数组类型。

1)转换为数组类型(en为一个枚举类型的实例)

1
2
FieldInfo fi = en.GetType().GetField(en.ToString());
object[] attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

  2)转换为字典类型(推荐)

1
2
3
4
Type enumType = typeof(T);
string[] fieldstrs = Enum.GetNames(enumType);
//随后循环即可
foreach (var item in fieldstrs)

  而第二种转换为字典的方式比较常见,代码都是类似的,博主从网络找到了两种类型的写法,大家可以参考下:

方法一:

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
public class EnumHelper 
    /// <summary> 
    /// 枚举转字典集合 
    /// </summary> 
    /// <typeparam name="T">枚举类名称</typeparam> 
    /// <param name="keyDefault">默认key值</param> 
    /// <param name="valueDefault">默认value值</param> 
    /// <returns>返回生成的字典集合</returns> 
    public static Dictionary<string, object> EnumListDic<T>(string keyDefault, string valueDefault = ""
    
        Dictionary<string, object> dicEnum = new Dictionary<string, object>(); 
        Type enumType = typeof(T); 
        if (!enumType.IsEnum) 
        
            return dicEnum; 
        
        if (!string.IsNullOrEmpty(keyDefault)) //判断是否添加默认选项 
        
            dicEnum.Add(keyDefault, valueDefault);  
        
        string[] fieldstrs = Enum.GetNames(enumType); //获取枚举字段数组 
        foreach (var item in fieldstrs)   
        
            string description = string.Empty; 
            var field = enumType.GetField(item); 
            object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组 
            if (arr != null && arr.Length > 0) 
            
                description = ((DescriptionAttribute)arr[0]).Description;   //属性描述 
            
            else 
            
                description = item;  //描述不存在取字段名称 
            
            dicEnum.Add(description, (int)Enum.Parse(enumType, item));  //不用枚举的value值作为字典key值的原因从枚举例子能看出来,其实这边应该判断他的值不存在,默认取字段名称 
        
        return dicEnum; 
    
 
public enum TestEmun 
    [Description("主系统")] 
    AAA = 1, 
    [Description("订单子系统")] 
    BBB = 2, 
    [Description("CRM子系统")] 
    CCC = 3
 
public ActionResult Index() 
 
    Dictionary<string,object> dropDic=EnumHelper.EnumListDic<TestEmun>("",""); 
    ViewBag.dropList = new SelectList(dropDic,"value","key"); 
    //随后在视图中直接使用 ViewBag.dropList 作为数据源就可以
    return View(); 
 }

  View视图加载数据源并渲染:

1
2
<!--绑定DropdownList 下拉列表 其他List Control也是类似的-->
@Html.DropDownList("dropList", null, new { })

  方法二:直接将枚举转为List<SelectListItem>类型的数据,这样用起来更方便

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
/// <summary> 
/// 枚举转字典集合 
/// </summary> 
/// <typeparam name="T">枚举类名称</typeparam> 
/// <param name="keyDefault">默认key值</param> 
/// <param name="valueDefault">默认value值</param> 
/// <returns>返回生成的字典集合</returns> 
public static List<SelectListItem> GetSelectListItem<T>(object keyDefault)
{
    List<SelectListItem> dicEnum = new List<SelectListItem>();
    Type enumType = typeof(T);
    if (!enumType.IsEnum)
        return dicEnum;
    string[] fieldstrs = Enum.GetNames(enumType); //获取枚举字段数组 
    foreach (var item in fieldstrs)
    {
        string description = string.Empty;
        var field = enumType.GetField(item);
        object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组 
        if (arr != null && arr.Length > 0)
            description = ((DescriptionAttribute)arr[0]).Description;   //属性描述 
        else
            description = item;  //描述不存在取字段名称 
        //判断是否添加默认选项 
        if (keyDefault != null && keyDefault.Equals(Enum.Parse(enumType, item)))
        {
            dicEnum.Add(new SelectListItem() { Text = description, Selected = true, Value = Enum.Parse(enumType, item).ToString() });
        }
        else
        {
            dicEnum.Add(new SelectListItem() { Text = description, Value = Enum.Parse(enumType, item).ToString() });
        }
    }
    return dicEnum;
}

  使用的时候直接调用GetSelectListItem方法即可,得到的是一个List<SelectListItem>类型的数据,这种数据格式类型在ASP.NET MVC的视图中是直接可以对List Control使用的。

注意:以上的方法一方法二都需要引入 System.Web.Mvc,注意引用

 

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2018-04-24 c#生成随机字符串
点击右上角即可分享
微信分享提示