mvc中枚举的使用和绑定枚举值到DropDownListFor

1.EnumManage.cs新建枚举类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Reflection;
using System.Web.Mvc;

namespace Manage.Extension
{
    //枚举
    public enum TableStatus
    {
        [EnumDisplayName("空台桌")]
        EmptyTable = 1,
        [EnumDisplayName("已出单")]
        Single = 2,
        [EnumDisplayName("未出单")]
        NoSingle = 3,
        [EnumDisplayName("预定台")]
        Schedule = 4,
        [EnumDisplayName("呼叫")]
        Call = 5,
        [EnumDisplayName("加菜")]
        AddDish = 6,
        [EnumDisplayName("下单")]
        Down = 7,
        [EnumDisplayName("结账")]
        Checkout = 8,
        

    }
    public class EnumDisplayNameAttribute : Attribute
    {
        private string _displayName;
        public EnumDisplayNameAttribute(string displayName)
        {

            this._displayName = displayName;

        }
        public string DisplayName
        {

            get { return _displayName; }

        }

    }
    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).ToString(), Value = ((int)e).ToString() });

            }

            return selectList;

        }

    }

}
    
2.新建辅助方法类EnumHtml.cs(  @Html.DropDownListFor(model => model.TableStatus, (List<SelectListItem>)ViewData["date"]) )

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Reflection;
using Manage.Extension;

namespace System.Web.Mvc
{
    public static class EnumHtml
    {
        
        //显示Enum类型的Name字段
        public static MvcHtmlString DisplayEnumName(this HtmlHelper htmlHelper, string enumTypeName, int value)
        {
            //"Manage.Extension."  EnumManage.cs的命名空间
            Type enumType = Type.GetType("Manage.Extension." + enumTypeName);
            if (!Enum.IsDefined(enumType, value))
            {
                return MvcHtmlString.Empty;
            }

            EnumDisplayNameAttribute[] EnumAttributes = (EnumDisplayNameAttribute[])(enumType.GetField(Enum.GetName(enumType, value))).GetCustomAttributes(typeof(EnumDisplayNameAttribute), false);

            if (EnumAttributes.Length > 0)
            {
                return MvcHtmlString.Create(EnumAttributes[0].DisplayName);
            }

            //如果只是要简单的返回枚举的Name值就只要这一行了
            return MvcHtmlString.Create(Enum.GetName(enumType, value));
        }
        
     }


}
  3.后台


public ActionResult Edit(int id = 0)
        {
            Table table = db.Tables.Find(id);
            if (table == null)
            {
                return HttpNotFound();

            }
            ViewData["date"] = Manage.Extension.EnumExt.GetSelectList(typeof(TableStatus));

            return View(table);

        }

4.view视图

index:

 @Html.DisplayEnumName("TableStatus",item.TableStatus.Value)

edit:

@Html.DropDownListFor(model => model.TableStatus, (List<SelectListItem>)ViewData["date"])

5.完毕

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。