幫助類 using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Web; namespace WebApplication5{ public cl ...
---幫助類
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
namespace WebApplication5
{
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 ActionResult Enums()
{
Dictionary<string, object> Droplist = EnumHelper.EnumListDic<Project_Emun>("請選擇", "-1");
//C#MVC的方便之處也在這裡,List 集合要與下拉框進行綁定可以直接綁定 ViewBag.dropList = new SelectList(list,"對象欄位1","對象欄位2","預設選擇");
ViewBag.Drop = new SelectList(Droplist, "value", "key");
return View();
}
--枚舉類
public enum Project_Emun
{
[Description("開始")]
開始 = 1,
[Description("中斷")]
中斷 = 2,
[Description("結束")]
結束 = 3,
[Description("回饋")]
回饋 = 4,
}