C# 枚举转换selectlistitem 及 MVC @Html.DropDownListFor() 调用详细

2021-03-19 02:26

阅读:511

标签:res   play   show   bool   des   data   @class   obj   The   


 

枚举转换方法

技术图片技术图片
        /// 
        /// 根据枚举返回 List
        /// 
        /// 
        /// true ---请选择--- 
        /// 如果值不为0 则按枚举值选择
        /// 
        public static List GetEnumDataSource(Type enumType, bool withEmpty, int topValue = 0)
        {
            List list = new List();

            if (withEmpty)
            {
                list.Add(new SelectListItem { Value = topValue.ToString(), Text = "--请选择--", Selected = true });
            }

            FieldInfo[] fields = enumType.GetFields();
            foreach (FieldInfo item in fields)
            {
                if (!item.FieldType.IsEnum)
                    continue;
                int value = (int)item.GetValue(null);
                if (value 0)
                    continue;
                string text = string.Empty;
                object[] attrs = item.GetCustomAttributes(false);
                foreach (object attr in attrs)
                {
                    DescriptionAttribute des = attr as DescriptionAttribute;
                    if (des == null)
                    {
                        continue;
                    }
                    else
                    {
                        text = des.Description;
                    }
                }
                if (topValue == value)
                {
                    list.Add(new SelectListItem { Value = value.ToString(), Text = text, Selected = true });
                }
                else
                {
                    list.Add(new SelectListItem { Value = value.ToString(), Text = text });
                }
               
            }

            return list;
        }
View Code

 

Controller:

技术图片技术图片
 var selectLists = EnumExtension.GetEnumDataSource(typeof(UserType), false, (int)result.Item.RoleId);
                TempData["RoleSalesList"] = selectLists;
View Code

 

View
@Html.DropDownListFor(model => model.RoleId , TempData["RoleSalesList"] as IEnumerable, new { @class = "form-control" } )

 

C# 枚举转换selectlistitem 及 MVC @Html.DropDownListFor() 调用详细

标签:res   play   show   bool   des   data   @class   obj   The   

原文地址:https://www.cnblogs.com/DataBase-123/p/11044937.html


评论


亲,登录后才可以留言!