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

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

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

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

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

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

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

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

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

方法一:

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视图加载数据源并渲染:

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

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

/// <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,注意引用

 

原文地址:https://www.cnblogs.com/fireicesion/p/10764386.html