场景描述

在web开发过程中,有时候需要根据Enum类型生成下拉菜单;

有时候在输出枚举类型的时候,又希望输出对应的更具描述性的字符串。

喜欢直接用中文的请无视本文

不多说,直接看代码。

以下代码借鉴自http://stackoverflow.com/

本文针对 Aspnet Mvc 4 开发而言

Enum定义

using System.ComponentModel;
namespace xxxxx.yyyyy
{
public enum EN_ArticleType
{
[Description("软装家饰")]
RuanZhuang=1, [Description("家居风水")]
FengShui, [Description("装修技巧")]
JiQiao, [Description("行业动态")]
DongTai, [Description("样板美图")]
MeiTu, [Description("人才招聘")]
Jobs
}
}

扩展HtmlHelper

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html; namespace xxxx.ExtendMethods
{
public static class HtmlHelperUtils
{
/// <summary>
/// Creates the DropDown List (HTML Select Element) from LINQ
/// Expression where the expression returns an Enum type.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MvcHtmlString DropDownListForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
where TModel : class
{
return htmlHelper.DropDownListForEnum(expression, null);
} public static MvcHtmlString DropDownListForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
where TModel : class
{
TProperty value = htmlHelper.ViewData.Model == null
? default(TProperty)
: expression.Compile()(htmlHelper.ViewData.Model);
string selected = value == null ? String.Empty : value.ToString();
if (htmlAttributes == null)
{
return htmlHelper.DropDownListFor(expression, createSelectList(expression.ReturnType, selected));
}
else
{
return htmlHelper.DropDownListFor(expression, createSelectList(expression.ReturnType, selected), htmlAttributes);
}
} /// <summary>
/// Creates the select list.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <param name="selectedItem">The selected item.</param>
/// <returns></returns>
private static IEnumerable<SelectListItem> createSelectList(Type enumType, string selectedItem)
{
return (from object item in Enum.GetValues(enumType)
let fi = enumType.GetField(item.ToString())
let attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault()
let title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description
select new SelectListItem
{
Value = item.ToString(),
Text = title,
Selected = selectedItem == item.ToString()
}).ToList();
}
}
}

视图层输出下拉菜单

 @Html.DropDownListForEnum(model => model.Type, new { @class = "col-sm-2" })

扩展Enum

using System;
using System.ComponentModel;
using System.Reflection; namespace xxxx.ExtendMethods
{
public static class EnumUtils
{
public static string GetEnumDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false); if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
}

输出Enum value对应的Description

@item.Type.GetEnumDescription()  //item是实体,Type是EN_ArticleType类型的属性

结束

请自行尝试。

:)

最新文章

  1. 最大似然判别法和Bayes公式判别法
  2. 【JSOI2010】Group 部落划分 BZOJ 1821
  3. Java JVM类加载机制
  4. 解决iOS9下隐藏App返回按钮文字导致的诡异闪屏问题
  5. 【BZOJ1002】[FJOI2007]轮状病毒 递推+高精度
  6. Breaking parallel loops in .NET C# using the Stop method z
  7. 当前项目与当前环境的JDK版本不匹配”Bad version number in .class file“
  8. JavaScript基本类型比较
  9. Anaconda虚拟环境
  10. 024_nginx之backlog坑
  11. linux 因内存不足而 kill 掉 java 程序
  12. 程序员快速掌握的UI设计技巧
  13. 初学HTML-5
  14. eclipse 报错Version 1.6.0_45 of the JVM is not suitable for this product. Version:1.7 or greater is required
  15. 浅谈MVC、MVP、MVVM
  16. Python开课复习10
  17. 推荐五星级C语言学习网站
  18. 7 -- Spring的基本用法 -- 11... 基于XML Schema的简化配置方式
  19. Markdown的写法
  20. 【原创】Linux常用脚本

热门文章

  1. org.apache.hadoop.security.AccessControlException: Permission denied: user=?, access=WRITE, inode=&quot;/&quot;:hadoop:supergroup:drwxr-xr-x 异常解决
  2. C#中调用HttpWebRequest类中Get/Post请求无故失效的诡异问题
  3. oAuth 认证
  4. 笨办法用js屏蔽被http劫持的浮动广告
  5. python3--网络爬虫--爬取图片
  6. NYOJ--20--搜索(dfs)--吝啬的国度
  7. 快捷使用Node Inspector调试NodeJS
  8. 敏捷视界:Scrum起源、Scrum术语
  9. oracle 内连接,外连接
  10. 1.怎样控制div中的图片居中