Razor 語法@Html.DropDownList,根據List集合或者枚舉生成Select標簽


1、根據List集合生成Select標簽,根據數據庫數據換成SelectListItem集合

Action 方法(也可使用下方的List集合的擴展方法):

1 var selectList = DBList.Select(f => new SelectListItem { Value = f.Key, Text = f.Value }).ToList();
2 selectList.Insert(0, new SelectListItem() { Value = "-1", Text = "請選擇" });
3 ViewData["selectList"] = selectList;

 

View視圖:

1 @Html.DropDownListFor(m => m.HandleBy, ViewData["selectList"] as IEnumerable<SelectListItem>, new { @class = "form-control selectWidth" })

 

2、根據枚舉擴展方法生成Select標簽

View視圖:

@Html.DropDownList("ContractStyle", new Model.Enums.ContractStyleType().ToSelectList(), "全部", new { @class = "form-control" })

 

擴展方法:

  1     public static class SelectListExtension
  2     {
  3         public static IEnumerable<SelectListItem> CreateRangeSelect(int nimNumber, int maxNumber, string formatter = null)
  4         {
  5             for (int i = nimNumber; i <= maxNumber; i++)
  6                 yield return new SelectListItem { Value = i.ToString(formatter), Text = i.ToString(formatter) };
  7         }
  8 
  9         public static IEnumerable<SelectListItem> ToSelectListItem(this Dictionary<int, string> items, string defaultValue = null)
 10         {
 11             if (!string.IsNullOrWhiteSpace(defaultValue))
 12                 yield return new SelectListItem { Value = "", Text = defaultValue };
 13 
 14             foreach (var item in items)
 15                 yield return new SelectListItem { Value = item.Key.ToString(), Text = item.Value };
 16         }
 17 
 18         public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
 19             where TEnum : struct, IComparable, IFormattable, IConvertible
 20         {
 21             var values = from TEnum e in Enum.GetValues(typeof(TEnum))
 22                          select new { Id = Convert.ToInt32(e), Name = GetEnumDescription(e) };
 23             return new SelectList(values, "Id", "Name");
 24         }
 25 
 26         /// <summary>將枚舉類型轉化為SelectListItem列表
 27         /// </summary>
 28         /// <typeparam name="TEnum"></typeparam>
 29         /// <param name="enumObject">The enum object.</param>
 30         /// <param name="firstItemText">The first item text.</param>
 31         /// <param name="selectedId">The selected identifier.</param>
 32         /// <returns></returns>
 33         public static List<SelectListItem> EnumToSelectListItems<TEnum>(string firstItemText = null, int selectedId = -1)
 34         {
 35             var selectList = new List<SelectListItem>();
 36 
 37             if (!string.IsNullOrEmpty(firstItemText))
 38             {
 39                 selectList.Add(new SelectListItem()
 40                 {
 41                     Value = "-1",
 42                     Text = firstItemText,
 43                     Selected = selectedId == -1
 44                 });
 45             }
 46             selectList.AddRange(from TEnum e in Enum.GetValues(typeof(TEnum))
 47                                 select new SelectListItem
 48                                 {
 49                                     Value = Convert.ToInt32(e).ToString(),
 50                                     Text = GetEnumDescription(e),
 51                                     Selected = Convert.ToInt32(e) == selectedId
 52                                 });
 53 
 54             return selectList;
 55         }
 56         public static List<SelectListItem> ToSelectListByFieldType<TEnum>(FieldTypeEnum? fieldType = null, string firstItemText = null, string firstItemValue = null, int selectedId = -1)
 57             where TEnum : struct, IComparable, IFormattable, IConvertible
 58         {
 59             var selectList = new List<SelectListItem>();
 60 
 61             if (!string.IsNullOrEmpty(firstItemText))
 62             {
 63                 selectList.Add(new SelectListItem()
 64                 {
 65                     Value = firstItemValue,
 66                     Text = firstItemText,
 67                     Selected = selectedId == -1
 68                 });
 69             }
 70             if (fieldType.HasValue)//指定枚舉字段類型,只返回特定類型列表
 71             {
 72                 foreach (TEnum e in Enum.GetValues(typeof(TEnum)))
 73                 {
 74                     FieldInfo fi = e.GetType().GetField(e.ToString());
 75                     EnumValueFieldTypeAttribute[] fieldTypeAttributes = (EnumValueFieldTypeAttribute[])fi.GetCustomAttributes(typeof(EnumValueFieldTypeAttribute), false);
 76                     if (fieldTypeAttributes == null || fieldTypeAttributes.Length == 0 || fieldTypeAttributes[0].FieldType != fieldType) continue;
 77                     var item = new SelectListItem
 78                     {
 79                         Value = Convert.ToInt32(e).ToString(),
 80                         Selected = Convert.ToInt32(e) == selectedId
 81                     };
 82                     DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
 83                     if ((attributes != null) && (attributes.Length > 0))
 84                         item.Text = attributes[0].Description;
 85                     else
 86                         item.Text = e.ToString();
 87                     selectList.Add(item);
 88                 }
 89             }
 90             else//不指定枚舉字段類型,顯示全部
 91             {
 92                 selectList.AddRange(from TEnum e in Enum.GetValues(typeof(TEnum))
 93                                     select new SelectListItem
 94                                     {
 95                                         Value = Convert.ToInt32(e).ToString(),
 96                                         Text = GetEnumDescription(e),
 97                                         Selected = Convert.ToInt32(e) == selectedId
 98                                     });
 99             }
100             return selectList;
101         }
102         public static string GetEnumDescription<TEnum>(TEnum value)
103         {
104             FieldInfo fi = value.GetType().GetField(value.ToString());
105 
106             DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
107 
108             if ((attributes != null) && (attributes.Length > 0))
109                 return attributes[0].Description;
110             else
111                 return value.ToString();
112         }
113 
114         /// <summary>將list轉換成SelectListItem列表
115         /// </summary>
116         /// <typeparam name="T"></typeparam>
117         /// <param name="list">列表數據</param>
118         /// <param name="firstItemText">第一個下拉框名稱(未空則不額外添加)</param>
119         /// <param name="selectedId">已選項id</param>
120         public static IEnumerable<SelectListItem> ListToSelectListItems<T>(this IEnumerable<T> list, string firstItemText, int selectedId = -1)
121         {
122             if (list == null)
123             {
124                 return new List<SelectListItem>();
125             }
126             var t = typeof(T);
127             List<SelectListItem> selectList = new List<SelectListItem>();
128             if (!string.IsNullOrEmpty(firstItemText))
129             {
130                 selectList.Add(new SelectListItem()
131                 {
132                     Value = "-1",
133                     Text = firstItemText,
134                     Selected = selectedId == -1
135                 });
136             }
137             foreach (var item in list)
138             {
139                 var addItem = new SelectListItem();
140                 foreach (var p in t.GetProperties())
141                 {
142                     //id(約定為int類型)
143                     if (p.PropertyType == typeof(System.Int32))
144                     {
145                         addItem.Value = p.GetValue(item).ToString();
146                     }
147                     else
148                     {//value
149                         addItem.Text = p.GetValue(item).ToString();
150                     }
151                     addItem.Selected = addItem.Value.Equals(selectedId);
152                 }
153                 selectList.Add(addItem);
154             }
155             return selectList;
156         }
157 
158 
159     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM