原文:MVC中下拉框显示枚举项

本篇将通过3种方式,把枚举项上的自定义属性填充到下拉框:
1、通过控制器返回List<SelectListItem>类型给前台视图
2、通过为枚举类型属性打上UIHint属性让模版显示枚举项
3、通过自定义元数据提供器DataAnnotationsModelMetadataProvider让模版显示枚举项

 

我们经常会把类型为Int16的属性通过枚举来获得。比如:

public class SomeClass
{
public int16 Status{get;set;}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

对应的枚举:

public enum StatusEnum
{
    Enable = 0,
    Disable = 1
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

在MVC视图中可能会这样写:

<select id="sel">
   <option value="">==选择状态==</option>
   <option value="0">启用</option>
   <option value="1">禁用</option>
</select>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

如果枚举的项发生变化怎么办?比如:

public enum StatusEnum
{
    Enable = 0,
    Disable = 1,
    NeverComeback = 2
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

如果修改每一页的代码,显然是不合理的。最理想的做法是:为每一个枚举项打上属性,显示的时候直接读取枚举以及枚举项属性值。

 

  通过控制器返回List<SelectListItem>类型给前台视图

定义一个Model,其中有一个类型为Int16的属性Status,这个属性用来接收枚举值。

using System;
using System.ComponentModel.DataAnnotations;
 
namespace MvcApplication1.Models
{
    public class Stadium
    {
        public int Id { get; set; }
 
        [Display(Name = "场馆名称")]
        public string Name { get; set; }
 
        [Display(Name = "是否启用")]
        public Int16 Status { get; set; }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

为每个枚举项打上的属性需要我们自定义,通过构造函数接收名称,并提供一个属性供外部访问。

using System;
 
namespace MvcApplication1.Extension
{
    public class EnumDisplayNameAttribute : Attribute
    {
        private string _displayName;
 
        public EnumDisplayNameAttribute(string displayName)
        {
            this._displayName = displayName;
        }
 
        public string DisplayName
        {
            get { return _displayName; }
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

为每个枚举项打上自定义属性。

using MvcApplication1.Extension;
 
namespace MvcApplication1.Models.Enum
{
    public enum StatusEnum
    {
        [EnumDisplayName("启用")]
        Enable = 0,
        [EnumDisplayName("禁用")]
        Disable =  1
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

我们的目的是在控制器获取List<SelectListItem>集合,然后传递到前台视图。现在,枚举和枚举项上的自定义属性都有了,有必要创建一个帮助类来帮我们获取List<SelectListItem>集合。

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
 
namespace MvcApplication1.Extension
{
    public class EnumExt
    {
        /// <summary>
        /// 根据枚举成员获取自定义属性EnumDisplayNameAttribute的属性DisplayName
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetEnumCustomDescription(object e)
        {
            //获取枚举的Type类型对象
            Type t = e.GetType();
 
            //获取枚举的所有字段
            FieldInfo[] ms = t.GetFields();
 
            //遍历所有枚举的所有字段
            foreach (FieldInfo f in ms)
            {
                if (f.Name != e.ToString())
                {
                    continue;
                }
 
                //第二个参数true表示查找EnumDisplayNameAttribute的继承链
                if (f.IsDefined(typeof (EnumDisplayNameAttribute), true))
                {
                    return
                        (f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), true)[0] as EnumDisplayNameAttribute)
                            .DisplayName;
                }
            }
 
            //如果没有找到自定义属性,直接返回属性项的名称
            return e.ToString();
        }
 
        /// <summary>
        /// 根据枚举,把枚举自定义特性EnumDisplayNameAttribut的Display属性值撞到SelectListItem中
        /// </summary>
        /// <param name="enumType">枚举</param>
        /// <returns></returns>
        public static List<SelectListItem> GetSelectList(Type enumType)
        {
            List<SelectListItem> selectList = new List<SelectListItem>();
            foreach (object e in Enum.GetValues(enumType))
            {
                selectList.Add(new SelectListItem(){Text = GetEnumCustomDescription(e),Value = ((int)e).ToString()});
            }
            return selectList;
        }
    }
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

在控制器中,通过ViewData把List<SelectListItem>集合往前台传。控制器包含2个方法,一个方法用来显示创建视图界面,另一个用来显示编辑视图界面。

        //创建
        public ActionResult Index()
        {
            ViewData["s"] = EnumExt.GetSelectList(typeof (StatusEnum));
            return View(new Stadium());
        }
 
        //编辑
        public ActionResult Edit()
        {
            Stadium s = new Stadium()
            {
                Id = 2,
                Name = "水立方",
                Status = (short)StatusEnum.Disable
            };
            ViewData["s"] = EnumExt.GetSelectList(typeof(StatusEnum));
            return View(s);
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

在强类型的创建视图界面中,通过@Html.DropDownListFor(model => model.Status,(List<SelectListItem>)ViewData["s"])接收来自控制器的数据。

@model MvcApplication1.Models.Stadium
 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>Index</h2>
 
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
 
    <fieldset>
        <legend>Stadium</legend>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Status)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Status,(List<SelectListItem>)ViewData["s"])
            @Html.ValidationMessageFor(model => model.Status)
        </div>
 
        <p>
            <input type="submit" value="添加" />
        </p>
    </fieldset>
}
 
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

在强类型的编辑视图界面中,同样通过@Html.DropDownListFor(model => model.Status,(List<SelectListItem>)ViewData["s"])接收来自控制器的数据。

@model MvcApplication1.Models.Stadium
 
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>Edit</h2>
 
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
 
    <fieldset>
        <legend>Stadium</legend>
 
        @Html.HiddenFor(model => model.Id)
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Status)
        </div>
        <div class="editor-field">
             @Html.DropDownListFor(model => model.Status,(List<SelectListItem>)ViewData["s"])
            @Html.ValidationMessageFor(model => model.Status)
        </div>
 
        <p>
            <input type="submit" value="编辑" />
        </p>
    </fieldset>
}
 
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

创建界面:

 

编辑界面:

 

  通过为枚举类型属性打上UIHint属性让模版显示枚举项

由于模版是根据属性类型来判断的,再定义一个Model,其中一个属性类型是枚举。

using System.ComponentModel.DataAnnotations;
using MvcApplication1.Models.Enum;
 
namespace MvcApplication1.Models
{
    public class Stadium1
    {
        public int Id { get; set; }
 
        [Display(Name = "场馆名称")]
        public string Name { get; set; }
 
        [Display(Name = "是否启用")]
        public StatusEnum Status { get; set; } 
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

在Views/Shared/EditorTemplates文件夹下创建Enum.cshtml,用来处理类型为Enum的属性。

@using System.ComponentModel.DataAnnotations
@using System.Reflection
@using MvcApplication1.Extension
 
@{
    var selectList = new List<SelectListItem>();
    string optionLabel = null;
    object htmlAttributes = null;
    var enumType = (Type)Model.GetType();
    foreach (var value in Enum.GetValues(enumType))
    {
        var field = enumType.GetField(value.ToString());
        var option = new SelectListItem() {Value = value.ToString()};
        var display = field.GetCustomAttributes(typeof (EnumDisplayNameAttribute), false).FirstOrDefault() as EnumDisplayNameAttribute;
        if (display != null)
        {
            option.Text = display.DisplayName;
        }
        else
        {
            option.Text = value.ToString();
        }
        option.Selected = object.Equals(value, Model);
        selectList.Add(option);
    }
}
 
@Html.DropDownList("",selectList, optionLabel, htmlAttributes)
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

控制器中有2个方法用来显示创建和编辑视图界面。

        //创建
        public ActionResult TemplateCreate()
        {
            return View(new Stadium1());
        }
 
        //编辑
        public ActionResult TemplateEdit()
        {
            Stadium1 s = new Stadium1()
            {
                Id = 2,
                Name = "水立方",
                Status = StatusEnum.Disable
            };
            return View(s);
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

强类型的创建视图界面:

@model MvcApplication1.Models.Stadium1
 
@{
    ViewBag.Title = "TemplateCreate";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>TemplateCreate</h2>
 
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
 
    <fieldset>
        <legend>Stadium</legend>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Status)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Status)
            @Html.ValidationMessageFor(model => model.Status)
        </div>
 
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
 
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

强类型的编辑视图界面:

@model MvcApplication1.Models.Stadium1
 
@{
    ViewBag.Title = "TemplateEdit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>TemplateEdit</h2>
 
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
 
    <fieldset>
        <legend>Stadium</legend>
 
        @Html.HiddenFor(model => model.Id)
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Status)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Status)
            @Html.ValidationMessageFor(model => model.Status)
        </div>
 
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}
 
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

最后,给Stadium1的枚举属性,打上UIHint属性,指明使用公共Enum类型模版Views/Shared/EditorTemplates/Enum.cshtml。

using System.ComponentModel.DataAnnotations;
using MvcApplication1.Models.Enum;
 
namespace MvcApplication1.Models
{
    public class Stadium1
    {
        public int Id { get; set; }
 
        [Display(Name = "场馆名称")]
        public string Name { get; set; }
 
        [Display(Name = "是否启用")]
        [UIHint("Enum")]
        public StatusEnum Status { get; set; } 
    }
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

创建视图界面:

编辑视图界面:

 

  通过自定义元数据提供器DataAnnotationsModelMetadataProvider让模版显示枚举项

如果觉得为属性打上[UIHint("Enum")]属性麻烦的话,还可以通过数据提供器,为所有类型为Enum的属性指明模版。

 

当然自定义的元数据提供器是需要在全局中注册的。

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
 
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
 
            //注册自定义元数据提供其
            ModelMetadataProviders.Current = new CustomMetadataProvider();
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

现在可以把Stadium的[UIHint("Enum")]注释掉。

 

  总结

如果,我们想在下拉框中显示枚举项,首先给枚举项打上自定义属性,通过反射可以拿到自定义属性的相关属性值。

如果,想在控制器方法中获取List<SelectListItem>集合往前台传,我们可以封装一个方法,根据枚举返回List<SelectListItem>集合;

如果想根据属性的类型显示枚举模版,要么给枚举属性打上[UIHint("Enum")],要么在全局自定义一个DataAnnotationsModelMetadataProvider。

MVC中下拉框显示枚举项的更多相关文章

  1. ASP.NET MVC之下拉框绑定四种方式(十)

    前言 上两节我们讲了文件上传的问题,关于这个上传的问题还未结束,我也在花时间做做分割大文件处理以及显示进度的问题,到时完成的话再发表,为了不耽误学习MVC其他内容的计划,我们今天开始好好讲讲关于MVC ...

  2. flex中下拉框的实现

    flex中下拉框的实现 <mx:ComboBox id = "combobox" dataProvider = "{deviceCodeType }" e ...

  3. jquery选中将select下拉框中一项后赋值给text文本框

    jquery选中将select下拉框中一项后赋值给text文本框,出现无法将第一个下拉框的value赋值给文本框 因为select默认选中第一项..在选择第一项时,便导致无法激发onchange事件. ...

  4. Bootstrap Flat UI的select下拉框显示不出来 问题解决

    Bootstrap Flat UI的select下拉框显示不出来?看这里,恰巧今天我也遇到了这个问题: 点击Messages后并没有出现下拉列表,然而官网的index.html却能显示出来. 经过一番 ...

  5. MVC视图中下拉框的使用

    一.一般变量或对象的绑定 首先要在controller 中将选项设置成 selecList对象,并赋值给viewBag动态对象. public ActionResult Index(string mo ...

  6. ASP.NET MVC 下拉框的传值的两种方式

    以前使用WebForm变成时,下拉框传值只需直接在后台绑定代码就可以了.现在我们来看看在MVC中DropDownList是如果和接受从Controller传过来的值的. 第一种:使用DropDownL ...

  7. jQuery Ajax MVC 下拉框联动

    无刷新下拉框联动方法: Controllers代码 public JsonResult DH_Change(string DH_ID) { List<SelectListItem> Tea ...

  8. Js获取下拉框当前选择项的文本和值

    现在有一个Id为AreaId的下拉框,要获取它当前选择项的文本和值有以下方法: <span class="red">* </span> 地       区: ...

  9. DevExpress GridControl 中下拉框联动效果的实现(及支持文本框录入情况)

    先解释一下标题: grid中的某一列默认为文本框,根据需要动态的变更为下拉框,且支持动态变更数据源 需求是这样的: 有一些参数(A),这些参数又分别对应另外的参数(B),所以,先把A作为一列,B根据A ...

随机推荐

  1. Python编程预约参观北京行动纲要

    通过Python程序来模拟一个统一平台预约参观北京,包含验证码识别.登陆.据医院.时间.有关主管部门号等查询. 此程序仅供学习使用,请勿用于其他用途. 1.验证码图片 def getCodePic() ...

  2. 玩转Web值jquery(一)---对表单中的某一标签批量处理(以input为例)

    jquery可以对form进行操作,以批量操作某一标签,这里以input标签为例总结. 示例一:对删除infoForm表单的input的所有readonly属性 $("#infoForm i ...

  3. Java Web整合开发(78) -- Struts 1

    在Struts1.3中已经取消了<data-sources>标签,也就是说只能在1.2版中配置,因为Apache不推荐在 struts-config.xml中配置数据源.所以建议不要在st ...

  4. 最近做RTSP流媒体的实时广播节目

    //h264视频流打包代码 // NALDecoder.cpp : Defines the entry point for the console application. #include < ...

  5. SignalR与ActiveMQ

    SignalR与ActiveMQ结合构建实时通信   一.概述 本教程主要阐释了如何利用SignalR与消息队列的结合,实现不同客户端的交互 SignalR如何和消息队列交互(暂使用ActiveMQ消 ...

  6. offsetTop和scrollTop差异

    最近写组件,这两个属性的结果搞的有点晕,我检查的文件及资料,这两个性质如下面总结: 他一直在offsetLeft.offsetTop,scrollLeft.scrollTop这些方法都是非常迷茫,花一 ...

  7. 左右presentViewController经background黑问题

    看效果图: 用例如以下代码,想弹出一个模态窗体,设置它的背景透明度为0.5,却发觉prsent后的背景色变为黑色的. ShareVC *share = [[ShareVC alloc] init]; ...

  8. 在 VS 类库项目中 Add Service References 和 Add Web References 的区别

    原文:在 VS 类库项目中 Add Service References 和 Add Web References 的区别 出身问题: 1.在vs2005时代,Add Web Reference(添加 ...

  9. java提高篇(八)-----实现多重继承

    多重继承指的是一个类可以同时从多于一个的父类那里继承行为和特征,然而我们知道Java为了保证数据安全,它只允许单继承.有些时候我们会认为如果系统中需要使用多重继承往往都是糟糕的设计,这个时候我们往往需 ...

  10. android数据储存之应用安装位置

    原文地址:http://developer.android.com/guide/topics/data/install-location.html#Compatiblity 从API8開始,你能够将你 ...