ASP.NET MVC 枚举类型转LIST CONTROL控件
在实际应用中,我们经常会用到下拉框、多选、单选等类似的控件,我们可以统称他们为List Control,他们可以说都是一种类型的控件,相同之处都是由一个或一组键值对的形式的数据进行绑定渲染而成的。
这些List Control的数据来源通常为数据库,固定值,但是有时候我们也会把数据写入在枚举或配置文件中,这篇文章针对数据写入枚举的情况下,如何在ASP.NET MVC中将枚举类型的数据读取并渲染成为List Control控件(下拉框、多选、单选等)
方法其实有很多种,但是疏通同归,基本都是先加载枚举类型,随后将枚举类型的数据转为字典类型或者数组类型。
1)转换为数组类型(en为一个枚举类型的实例)
FieldInfo fi = en.GetType().GetField(en.ToString());
object[] attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
2)转换为字典类型(推荐)
Type enumType = typeof(T);
string[] fieldstrs = Enum.GetNames(enumType);
//随后循环即可
foreach (var item in fieldstrs)
而第二种转换为字典的方式比较常见,代码都是类似的,博主从网络找到了两种类型的写法,大家可以参考下:
方法一:
public class EnumHelper
{
/// <summary>
/// 枚举转字典集合
/// </summary>
/// <typeparam name="T">枚举类名称</typeparam>
/// <param name="keyDefault">默认key值</param>
/// <param name="valueDefault">默认value值</param>
/// <returns>返回生成的字典集合</returns>
public static Dictionary<string, object> EnumListDic<T>(string keyDefault, string valueDefault = "")
{
Dictionary<string, object> dicEnum = new Dictionary<string, object>();
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
return dicEnum;
}
if (!string.IsNullOrEmpty(keyDefault)) //判断是否添加默认选项
{
dicEnum.Add(keyDefault, valueDefault);
}
string[] fieldstrs = Enum.GetNames(enumType); //获取枚举字段数组
foreach (var item in fieldstrs)
{
string description = string.Empty;
var field = enumType.GetField(item);
object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组
if (arr != null && arr.Length > 0)
{
description = ((DescriptionAttribute)arr[0]).Description; //属性描述
}
else
{
description = item; //描述不存在取字段名称
}
dicEnum.Add(description, (int)Enum.Parse(enumType, item)); //不用枚举的value值作为字典key值的原因从枚举例子能看出来,其实这边应该判断他的值不存在,默认取字段名称
}
return dicEnum;
}
} public enum TestEmun
{
[Description("主系统")]
AAA = 1,
[Description("订单子系统")]
BBB = 2,
[Description("CRM子系统")]
CCC = 3
} public ActionResult Index()
{
Dictionary<string,object> dropDic=EnumHelper.EnumListDic<TestEmun>("","");
ViewBag.dropList = new SelectList(dropDic,"value","key");
//随后在视图中直接使用 ViewBag.dropList 作为数据源就可以
return View();
}
View视图加载数据源并渲染:
<!--绑定DropdownList 下拉列表 其他List Control也是类似的-->
@Html.DropDownList("dropList", null, new { })
方法二:直接将枚举转为List<SelectListItem>类型的数据,这样用起来更方便
/// <summary>
/// 枚举转字典集合
/// </summary>
/// <typeparam name="T">枚举类名称</typeparam>
/// <param name="keyDefault">默认key值</param>
/// <param name="valueDefault">默认value值</param>
/// <returns>返回生成的字典集合</returns>
public static List<SelectListItem> GetSelectListItem<T>(object keyDefault)
{
List<SelectListItem> dicEnum = new List<SelectListItem>();
Type enumType = typeof(T);
if (!enumType.IsEnum)
return dicEnum;
string[] fieldstrs = Enum.GetNames(enumType); //获取枚举字段数组
foreach (var item in fieldstrs)
{
string description = string.Empty;
var field = enumType.GetField(item);
object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组
if (arr != null && arr.Length > 0)
description = ((DescriptionAttribute)arr[0]).Description; //属性描述
else
description = item; //描述不存在取字段名称
//判断是否添加默认选项
if (keyDefault != null && keyDefault.Equals(Enum.Parse(enumType, item)))
{
dicEnum.Add(new SelectListItem() { Text = description, Selected = true, Value = Enum.Parse(enumType, item).ToString() });
}
else
{
dicEnum.Add(new SelectListItem() { Text = description, Value = Enum.Parse(enumType, item).ToString() });
}
}
return dicEnum;
}
使用的时候直接调用GetSelectListItem方法即可,得到的是一个List<SelectListItem>类型的数据,这种数据格式类型在ASP.NET MVC的视图中是直接可以对List Control使用的。
注意:以上的方法一方法二都需要引入 System.Web.Mvc,注意引用
ASP.NET MVC 枚举类型转LIST CONTROL控件的更多相关文章
- 【番外篇】ASP.NET MVC快速入门之免费jQuery控件库(MVC5+EF6)
目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...
- ASP.NET MVC显示WebForm网页或UserControl控件
ASP.NET MVC显示WebForm网页或UserControl控件 学习与使用ASP.NET MVC这样久,还是对asp.net念念不忘.能否在asp.net mvc去显示aspx或是user ...
- ASP.NET MVC中加载WebForms用户控件(.ascx)
原文:ASP.NET MVC中加载WebForms用户控件(.ascx) 问题背景 博客园博客中的日历用的是ASP.NET WebForms的日历控件(System.Web.UI.WebControl ...
- 念念不忘,ASP.NET MVC显示WebForm网页或UserControl控件
学习与使用ASP.NET MVC这样久,还是对asp.net念念不忘.能否在asp.net mvc去显示aspx或是user control呢?这个灵感(算不上灵感,只能算是想法)是来自前些天有写过一 ...
- asp.net MVC 枚举类型的处理的几种方式
枚举类型本质上是int类型,整型,这是非常重要的一点. 可以使用(int)将它强制转换为 整形.如果要使用MVC5提供的新辅助方法@Html.EnumDropDownListFor()方法,就必须将枚 ...
- Asp.Net 将枚举类型(enum)绑定到ListControl(DropDownList)控件
在开发过程中一些状态的表示使用到枚举类型,那么如何将枚举类型直接绑定到ListControl(DropDownList)是本次的主题,废话不多说了,直接代码: 首先看工具类代码: /// <su ...
- ASP.NET MVC 描述类型(二)
ASP.NET MVC 描述类型(二) 前言 上个篇幅中说到ControllerDescriptor类型的由来过程,对于ControllerDescriptor类型来言ActionDescriptor ...
- ASP.NET MVC 描述类型(一)
ASP.NET MVC 描述类型(一) 前言 在前面的好多篇幅中都有提到过ControllerDescriptor类型,并且在ASP.NET MVC 过滤器(一)篇幅中简单的描述过,今天我们就来讲一下 ...
- Asp.Net Mvc 返回类型总结
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
随机推荐
- 以方法调用的原理解释Ruby中“puts ‘Hello‘”
这里尽管缺少消息发送所需要的点(.)以及该消息的显示接收者,却依然发送了消息puts并传递了参数“Hello”给一个对象:默认对象self.在程序运行期间,虽然作为self的对象通过特定规则发生改变, ...
- Navicat连接Mysql报错:Client does not support authentication protocol requested by server;
Navicat连接Mysql报错:Client does not support authentication protocol requested by server: 刚安装Mysql,想用Nav ...
- 关于while read line 循环中变量作用域的问题
前一阵用shell写了一个从数据库中抽取数据生成.xml文件的脚本,要求是每个文件中只生成1000条数据.于是用到了while read line 作为循环. 在制作文件计数器的时候发现了一个问题,在 ...
- CentOS Linux 升级内核步骤和方法(转)
当前系统为CentOS Linux release 6.0 (Final),内核版本为2.6.32-71.el6.i686.由于最近内核出现最新的漏洞(linux kernel 又爆内存提权漏洞,2. ...
- Go Lang
IDE: https://www.jetbrains.com/products.html?fromMenu#type=ide Study: http://www.runoob.com/go/go-en ...
- UpdatePanel 控件,客户端事件生命周期踩坑
<script type="text/javascript" language="javascript"> Sys.WebForms.PageReq ...
- 大学生对vivo手机的看法
- GLog 初始化说明
#include <iostream> #include <glog/logging.h> int main(int argc, char* argv[]) { google: ...
- Python标准库之textwrap模块
textwrap通过调整换行符的位置来格式化文本:以下是全部方法 __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shor ...
- 垃圾回收(GC Garbage collection)
JS有自动垃圾清理机制, 如果有不需要用的对象,只需要设置对象=null即可 Var a = new object() a = null