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     }

 


欢迎关注公众号:DotNet软件编程IT技术

 

posted @ 2018-01-31 10:09  maxmo  阅读(2705)  评论(0编辑  收藏  举报

欢迎关注公众号:DotNet软件编程IT技术

欢迎关注公众号:DotNet软件编程IT技术