场景描述

在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. Python学习记录----IDE安装

    摘要: 安装eric5 一 确定python版本 安装的最新版本:python3.3 下载连接:http://www.python.org/getit/ 二 确定pyqt版本 安装的最新版本:PyQt ...

  2. [HNOI2006]超级英雄 网络流+二分版

    刚学网络流的我这里有一道非常好的"网络流练手题"------[HNOI2006]超级英雄. 记得很久以前真的有这个节目来着,还是大兵主持的. 其实这是一道匈牙利板子大水题,但对于我 ...

  3. APMServ中的 Apache无法启动…

    情况1. 找问题:C:\APMServ5.2.6\Apache\bin点击httpd.exe 会出现: path is invalid.(地址无效) 解决办法:找到C:/APMServ5.2.6/Ap ...

  4. ARP与RARP协议及arp脚本

    1.什么是ARP与RARP协议 地址解析协议,即ARP(Address Resolution Protocol),是根据IP地址获取物理地址的一个TCP/IP协议. 在⽹络通讯时,源主机的应⽤程序知道 ...

  5. React Native 系列(五) -- 组件间传值

    前言 本系列是基于React Native版本号0.44.3写的.任何一款 App 都有界面之间数据传递的这个步骤的,那么在RN中,组件间是怎么传值的呢?这篇文章将介绍到顺传.逆传已经通过通知传值. ...

  6. java中List Array相互转换

    List to Array List 提供了toArray的接口,所以可以直接调用,转为object型数组 List<String> list = new ArrayList<Str ...

  7. nio系列(一)---nio重要组成

    nio重要组成部分 前言:通过本文可以了解nio的重要组成部分,了解完基础的内容后后面理解才会简单一点.下一篇会讲讲nio的应用和io的对比.如果有不正确的地方还望指正. channel chanel ...

  8. 分页工具类 BaseAction

    package com.xxxxxxx.bos.web.action.common; import java.io.IOException; import java.lang.reflect.Para ...

  9. MATLAB中多行注释以及取消的快捷键

    多行注释:Ctrl+R 取消注释:Ctrl +T

  10. 使用EasyWechat快速开发微信支付

    前期准备: 申请微信支付后, 会收到2个参数, 商户id,和商户key.注意,这2个参数,不要和微信的参数混淆.微信参数: appid, appkey, token支付参数: merchant_id( ...