场景描述

在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类型的属性

结束

请自行尝试。

:)

[2014-09-21]如何在 Asp.net Mvc 开发过程中更好的使用Enum的更多相关文章

  1. asp.net mvc开发过程中的一些小细节

    现在做网站用mvc越来越普及了,其好处就不说了,在这里只记录一些很多人都容易忽视的地方. 引用本地css和js文件的写法 这应该是最不受重视的地方,有同事也说我有点小题大作,但我觉得用mvc还是得有一 ...

  2. asp.net MVC开发过程中,使用到的方法(内置方法及使用说明)

    ® 视图的返回使用案例: [HttpGet] [SupportFilter] public ActionResult UserTopic(string type, string TopPicId, s ...

  3. 在 ASP.NET MVC 项目中使用 WebForm、 HTML

    原文地址:http://www.cnblogs.com/snowdream/archive/2009/04/17/winforms-in-mvc.html ASP.NET MVC和WebForm各有各 ...

  4. 如何在 ASP.NET MVC 中集成 AngularJS(3)

    今天来为大家介绍如何在 ASP.NET MVC 中集成 AngularJS 的最后一部分内容. 调试路由表 - HTML 缓存清除 就在我以为示例应用程序完成之后,我意识到,我必须提供两个版本的路由表 ...

  5. 如何在 ASP.NET MVC 中集成 AngularJS(2)

    在如何在 ASP.NET MVC 中集成 AngularJS(1)中,我们介绍了 ASP.NET MVC 捆绑和压缩.应用程序版本自动刷新和工程构建等内容. 下面介绍如何在 ASP.NET MVC 中 ...

  6. 如何在 ASP.NET MVC 中集成 AngularJS(1)

    介绍 当涉及到计算机软件的开发时,我想运用所有的最新技术.例如,前端使用最新的 JavaScript 技术,服务器端使用最新的基于 REST 的 Web API 服务.另外,还有最新的数据库技术.最新 ...

  7. 如何在asp.net mvc中添加自定义的HTML辅助种方法

    很久没在博客园发表文章了,今天来总结一下如何在asp.net mvc中添加自定义的HTML辅助方法.我们现在设计这么一个目前,利用自定义的HTML方法来渲染一个普通的img标记.直接进入主题吧: 首先 ...

  8. 如何在ASP.NET MVC为Action定义筛选器

    在ASP.NET MVC中,经常会用到[Required]等特性,在MVC中,同样可以为Action自定义筛选器,来描述控制器所遵守的规则. 首先,我们在ASP.NET MVC项目中定义一个TestC ...

  9. 【初学者指南】在ASP.NET MVC 5中创建GridView

    介绍 在这篇文章中,我们将会学习如何在 ASP.NET MVC 中创建一个 gridview,就像 ASP.NET Web 表单中的 gridview 一样.服务器端和客户端有许多可用的第三方库,这些 ...

随机推荐

  1. DL4NLP——词表示模型(三)word2vec(CBOW/Skip-gram)的加速:Hierarchical Softmax与Negative Sampling

    上篇博文提到,原始的CBOW / Skip-gram模型虽然去掉了NPLM中的隐藏层从而减少了耗时,但由于输出层仍然是softmax(),所以实际上依然“impractical”.所以接下来就介绍一下 ...

  2. 初学安卓开发随笔之 Intent 用法

    首先,对于安卓开发,目前世界上流行的是使用的是Android studio 2.0 .(hh 学着来呗 书上说用这个,,) 今后就定一个计划 每天更新一个Android 随笔,增强一下自控力吧!!! ...

  3. iOS开发实战-卫P嗯上网项目

    写在前面 最近闲来无事,又跟小伙伴搞起.一.键.上.网.的项目,于是这个项目就来了. 很高兴App 已经过审 有兴趣的可以玩玩牛牛数据

  4. dubbo&hsf&spring-cloud简单介绍

    Dubbo: 简介:Dubbo是一个分布式服务框架,以及SOA治理方案.其功能主要包括:高性能NIO通讯及多协议集成,服务动态寻址与路由,软负载均衡与容错,依赖分析与降级等. 底部NIO基于netty ...

  5. JVM学习笔记二:垃圾收集算法

    垃圾回收要解决的问题: 哪些内存需要回收? 线程私有区域不需要回收,如PC.Stack.Native Stack:Java 堆和方法区需要 什么时候回收? 以后的文章解答 如何回收? 首先进行对象存活 ...

  6. vue-cli的webpack模板项目配置文件分析

    由于最近在vue-cli生成的webpack模板项目的基础上写一个小东西,开发过程中需要改动到build和config里面一些相关的配置,所以刚好趁此机会将所有配置文件看一遍,理一理思路,也便于以后修 ...

  7. 创建 overlay 网络 - 每天5分钟玩转 Docker 容器技术(50)

    上一节我们搭建好实验环境,配置并运行了consul,今天开始创建 overlay 网络. 在 host1 中创建 overlay 网络 ov_net1: -d overlay 指定 driver 为 ...

  8. HDU5727 Necklace(二分图匹配)

    Problem Description SJX has 2*N magic gems. N of them have Yin energy inside while others have Yang ...

  9. vc操作电脑之常用命令

    1.重启计算机: ExitWindowsEx(EWX_REBOOT,0); 2.关机: ExitWindowsEx(EWX_SHUTDOWN,0); 3.注销: ExitWindowsEx(EWX_L ...

  10. Linux Command Line(II): Intermediate

    Prerequisite: Linux Command Line(I): Beginner ================================ File I/O $ cat > a ...