枚举的绑定

一:枚举的绑定
定义一个枚举
public enum ArticleCategory
    {
        /// <summary>
        /// 头条
        /// </summary>
        Headlines = 10,
 
        /// <summary>
        /// 资讯
        /// </summary>
        Imformation = 20,
 
        /// <summary>
        /// 学术
        /// </summary>
        Academic = 30,
 
    }
 
绑定枚举
后台字典形式
protected Dictionary<string, string> dtErrors = new Dictionary<string, string>();
 string strKey = string.Empty;
            string strValue = string.Empty;
            foreach (int intError in Enum.GetValues(typeof(ArticleCategory)))
            {
                strKey = intError.ToString();
                strValue = Enum.GetName(typeof(ArticleCategory), intError);
                dtErrors.Add(strKey, strValue);
            }
前台绑定
 <select id="selType">
                                <option value="0">-请选择分类-</option>
                                <% foreach (KeyValuePair<string, string> oneKeyValue in dtErrors)
                                   {%>
                                <option value="<%=oneKeyValue.Key %>">
                                    <%=oneKeyValue.Value%></option>
                                <%} %>
                            </select>
上面这种绑定好球麻烦
 <select id="selType">
                                <option value="0">-请选择分类-</option>
                                <% foreach (int intError in Enum.GetValues(typeof(ArticleCategory)))
                                   {%>
                                <option value="<%= intError.ToString() %>">
                                    <%=Enum.GetName(typeof(ArticleCategory), intError)%></option>
                                <%} %>
                            </select>
但是  这里面的select不能有server  否则就会显示上下文不支持此代码块。。。。
二:获取枚举描述

1、定义枚举

public enum EnumTest
{
[Description("开始")]
开始 = 1,
[Description("结束")]
结束 = 2,
[Description("运行中")]
运行中 = 3
}

2、扩展函数

引入命名空间

using System.ComponentModel;
using System.Reflection;

public static string GetEnumDesc(this Enum enumName)
{

Type type = enumName.GetType();
MemberInfo[] meminfo = type.GetMember(enumName.ToString());
if (meminfo != null && meminfo.Length > 0)
{
object[] obj = meminfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (obj != null && obj.Length > 0)
{
return ((DescriptionAttribute)obj[0]).Description;
}
}
return enumName.ToString();
}

调用方式:EnumTest.开始.GetEnumDesc();

作者:D调灬仔
出处:https://www.cnblogs.com/chj929555796/
您的推荐是我最大的动力,如果觉得这篇文章对你有帮助的话,请点个“推荐”哦,博主在此感谢!
原文地址:https://www.cnblogs.com/chj929555796/p/4375303.html