c# select标签绑定枚举,并以Description做Text显示
今天在做項(xiàng)目時(shí)遇到一個(gè)問題:
開發(fā)中有些字段是枚舉類型如 Dept 企業(yè)表中可能有個(gè)字段?Property 性質(zhì) 0:事業(yè)單位,1:私企,2:外企,但有時(shí)我們不會(huì)單獨(dú)為性質(zhì)這個(gè)字段定義一張表,
而是在后臺(tái)用枚舉來定義此字段有可能的值,而這個(gè)時(shí)候我們?cè)谇芭_(tái)綁定select標(biāo)簽時(shí)又不好將其寫死。
我首先想到的是用枚舉綁定select,但一般情況下我們的枚舉名都用英文表示,而將英文綁定就顯得不合實(shí)際,這時(shí)候我想到的是綁定 Description 枚舉描述。
下面是我的解決方案,本人小白,有更好的方法歡迎大家提出,一起加油共同進(jìn)步。
?
一.定義枚舉類 (common)
1 /// <summary> 2 /// 單位性質(zhì) 0:事業(yè)單位,1:私企,2:外企 3 /// </summary> 4 public enum DeptProperty 5 { 6 [Description("事業(yè)單位")] 7 Institution = 0, 8 [Description("私企")] 9 PrivateCompany = 1, 10 [Description("外企")] 11 ForeignCompany = 2 12 }二.獲取枚舉中的值和Description
ps:這塊方法可能不是最好的。有更好的方法希望能提出交流。
1.Controller.cs
1 /// <summary> 2 /// 獲取企業(yè)性質(zhì) 3 /// </summary> 4 public JsonResult GetDeptProperty() 5 { 6 List<SelectListItem> items = new List<SelectListItem>(); 7 //遍歷枚舉的公共且靜態(tài)的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 /// 根據(jù)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 }三.前臺(tái)請(qǐng)求數(shù)據(jù)并綁定 (js)
?
1 //加載企業(yè)性質(zhì) 2 function getDeptProperty() { 3 //同步請(qǐng)求以免后面的操作獲取不到值 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 }?
效果:
?
轉(zhuǎn)載于:https://www.cnblogs.com/feigao/p/4673219.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的c# select标签绑定枚举,并以Description做Text显示的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计组之存储系统:3、主存与CPU的链接(
- 下一篇: c# char unsigned_dll