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技术

Razor 语法@Html.DropDownList,根据List集合或者枚举生成Select标签的更多相关文章
- 知识点2-5:了解Razor语法
以往开发ASP.NET Web Form时,在ASPX页面上都会出现许多夹杂C#/VB.NET与HTML的情况,而先前使用<%...%>这种传统圆角括号的表示法会让HTML标签与ASP.N ...
- 5.3 Razor语法基础
以往开发ASP.NET Web Form时,在ASPX页面上都会出现许多夹杂C#/VB.NET与HTML的情况,而先前使用<%...%>这种传统圆角括号的表示法会让HTML标签与ASP.N ...
- ASP.NET Core 中文文档 第四章 MVC(3.2)Razor 语法参考
原文:Razor Syntax Reference 作者:Taylor Mullen.Rick Anderson 翻译:刘怡(AlexLEWIS) 校对:何镇汐 什么是 Razor? Razor 是一 ...
- [ASP.NET MVC 小牛之路]03 - Razor语法
本人博客已转移至:http://www.exblr.com/liam Razor是MVC3中才有的新的视图引擎.我们知道,在ASP.NET中,ASPX的视图引擎依靠<%和%>来调用C#指 ...
- MVC Razor语法
Razor语法, 视图引擎 Razor(CSHTML) @ 可以编写一条C#语句@{} 可以编写一组C#语句,也有可能嵌着Html@: 将文字内容直接输出到页面上去@() 在一句中将一段C#代码包括起 ...
- Razor语法&ActionResult&MVC
Razor代码复用 mvc 4 razor语法讲解和使用 了解ASP.NET MVC几种ActionResult的本质:EmptyResult & ContentResult 了解ASP.NE ...
- ASP.NET MVC Razor语法
ASP.NET MVC Razor语法 (一) 关于_ViewStart.cshtml文件 使用Razor模板引擎的话,会自动生成一个_ViewStart.cshtml文件.事实上,_View ...
- ASP.NET MVC中的Razor语法
1.Razor的基本语法 @* 多行代码时需要包含在大括号内{}和每句代码后都需要加分号; *@ @{ ViewBag.Title = "Index"; ViewBag.Name ...
- ASP.NET使用Razor语法无法正确识别.cshtml文件
ASP.NET使用WebPage编程的好处之一是可以使用强大的Razor语法, 但初次使用Razor语法会碰到一个比较头疼的问题就是无法直接写一个.cshtml让浏览器去识别,查资料也没有找到相关问题 ...
- mvc 4 razor语法讲解和使用
1.这里的 @{Layout="文件路径";} 代码块指定了整个项目默认所使用的布局文件(如图:) @RenderBody()对于所有的页面默认的情况下都会使用这个布局(Web ...
随机推荐
- 多维数组、Arrays类、稀疏数组、冒泡排序
多维数组 多维数组可以看成是数组的数组 比如二维数组就是一个特殊的一堆数组 其中每个元素就是一个数组. 二维数组: int a[][] = new int[2][5]; 解析:二维数组a可以看成一个两 ...
- dtd的三种引入方式
- SQL注入上传文件获取shell
SQL注入写文件的三个必要条件 Web目录有读写权限: 当目标网站的Web目录具有读写权限时,攻击者可以通过注入恶意SQL语句将恶意文件写入服务器上的Web目录. 知道文件的绝对路径: 攻击者需要知道 ...
- springboot整合hibernate(非JPA)(一)
springboot整合hibernate(非JPA)(一) springboot整合hibernate,非jpa,若是jpa就简单了,但是公司项目只有hibernate,并要求支持多数据库,因此记录 ...
- Rabin-Karp 字符串查找算法
和一般的比较字符串的方式不同,Rabin-Karp 查找算法通过对子字符串进行 hash,如果在原有字符串中找到了 hash 值相同的字符串,那么继续比较是否是需要查找的字串,一般来讲,如果 hash ...
- UE5:相机震动CameraShake源码分析
本文将会分析UE5中相机震动的调用流程,会简要地分析UCameraModifier_CameraShake.UCameraShakeBase等相关类的调用过程. 阅读本文,你至少需要使用或者了解过Ca ...
- Visual Studio 2022 Preview设置简体中文
前言: 作为尝鲜小分队队长,对于vs的升级版Visual Studio 2022 Preview肯定也开始用上了,不过之前一直以为还没有出中文的语言包所以一直用的是英文版的,搞得英文本来不好的我很是不 ...
- .NET技术分享日活动20221022
2022年10月22日下午,个人组织举办了山东地区的第六次.NET技术分享日活动.围绕.NET.低代码Low Code.云原生 Cloud Native.大数据.算法等方向进行创新技术的实践分享. 本 ...
- C# 创建Excel气泡图
气泡图(Bubble Chart)是可用于展示三个变量之间的关系.通过绘制x 值, y 值和大小值即可确定图表中气泡的坐标及大小.下面通过后端C#代码及VB.NET代码展示如何来实现在Excel中创建 ...
- 实战案例丨ModelArts在数据标注、数据过滤上的应用技巧:自动分组
大量复杂.乱序的图片依次标注效率极低,如果一次可以标注一大片的图片将极大地提升标注效率. 自动分组识别并提取图像特征,通过ModelArts先进的聚类算法可以将所有图片分组:将特征相似的图片归为一类, ...