MVC将枚举类型绑定到下拉框

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ao123056/article/details/86291446

项目中,有时候会遇到一些固定的选择框的值,如果直接写固定值,遇到好几处用到的地方,到修改的时候比较麻烦。

可以将其存到数据库中,也或者是存为枚举类型,修改也比较方便。

具体用法,枚举如下:

    /// <summary>
    /// 类别
    /// </summary>
    public enum SchemeType
    {
        [Description("评定方案1")]
        CompanyAssessment = 0,
        [Description("沟通方案1")]
        CompanyCommunication = 1,
        [Description("公告")]
        Announcement = 2,
        [Description("评定方案2")]
        CadreAssessment = 10,
        [Description("沟通方案2")]
        CadreCommunication = 11


    }

我们可以在controller中这样取值

 var allTypes = EnumHelper.GetAllEnums<SchemeType>(SchemeType.CompanyAssessment);
 ViewBag.allTypes = allTypes;

其中GetAllEnums方法如下:

        /// <summary>
        /// 获取全部的枚举项的值及描述
        /// </summary>
        /// <param name="obj">任意一个枚举值</param>
        /// <returns></returns>
        public static Dictionary<int, string> GetAllEnums<T>(T obj)
        {
            Type enumType = obj.GetType();
            Dictionary<int, string> results = new Dictionary<int, string>();
            foreach (var item in Enum.GetValues(enumType))
            {
                int value = Convert.ToInt32(item);
                string name = item.ToString();
                var enumValue = Enum.Parse(enumType, name);
                string s = GetObjDescription(enumValue);
                if (!string.IsNullOrEmpty(s)) name = s;
                results.Add(value, name);
            }
            return results;
        } 
 <span>方案类型:</span>
        <select id="FType" class="easyui-combobox" name="FType" style="width:200px;">
            <option value="">--全部--</option>
            @foreach (KeyValuePair<int, string> item in ViewBag.allTypes as Dictionary<int, string>)
            {
                <option value="@item.Key">@item.Value</option>
            }          
        </select>

这样就可以绑定到下拉框了显示的Text是[Description("评定方案1")]中的文字,Value值是数值 0、1等

猜你喜欢

转载自blog.csdn.net/ao123056/article/details/86291446
今日推荐