今天在做项目时遇到一个问题:
开发中有些字段是枚举类型如 Dept 企业表中可能有个字段Property 性质 0:事业单位,1:私企,2:外企,但有时我们不会单独为性质这个字段定义一张表,
而是在后台用枚举来定义此字段有可能的值,而这个时候我们在前台绑定select标签时又不好将其写死。
我首先想到的是用枚举绑定select,但一般情况下我们的枚举名都用英文表示,而将英文绑定就显得不合实际,这时候我想到的是绑定 Description 枚举描述。
下面是我的解决方案,本人小白,有更好的方法欢迎大家提出,一起加油共同进步。
一.定义枚举类 (common)
1 /// <summary> 2 /// 单位性质 0:事业单位,1:私企,2:外企 3 /// </summary> 4 public enum DeptProperty 5 { 6 [Description("事业单位")] 7 Institution = 0, 8 [Description("私企")] 9 PrivateCompany = 1,10 [Description("外企")]11 ForeignCompany = 212 }
二.获取枚举中的值和Description
ps:这块方法可能不是最好的。有更好的方法希望能提出交流。
1.Controller.cs
1 /// <summary> 2 /// 获取企业性质 3 /// </summary> 4 public JsonResult GetDeptProperty() 5 { 6 List<SelectListItem> items = new List<SelectListItem>(); 7 //遍历枚举的公共且静态的Field,获取Field的值; 8 foreach (FieldInfo myEnum in typeof(Model.EnumClass.DeptProperty).GetFields(BindingFlags.Public | BindingFlags.Static)) 9 {10 items.Add(new SelectListItem()11 {12 Text = EnumHelper.GetDescription(myEnum),13 Value = ((int)myEnum.GetValue(null)).ToString()14 });15 }16 return Json(items, JsonRequestBehavior.AllowGet);17 }
2.Helper.cs GetDescription()
1 /// <summary> 2 /// 根据Field获取Description说明的值 3 /// </summary> 4 /// <param name="fi"></param> 5 /// <returns></returns> 6 public static string GetDescription(FieldInfo fi) 7 { 8 DescriptionAttribute[] arrDesc = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); 9 return arrDesc[0].Description;10 }
三.前台请求数据并绑定 (js)
1 //加载企业性质 2 function getDeptProperty() { 3//同步请求以免后面的操作获取不到值 4$.ajaxSettings.async = false; 5$.getJSON('/PracticeEnterprise/GetDeptProperty', function (data) { 6 $('#deptProperty').empty(); 7 $.each(data, function (i, item) { 8 $('#deptProperty').append($('<option></option>').val(item.Value).text(item.Text)); 9 });10});11 }
效果: