1. 程式人生 > >MVC將列舉型別繫結到下拉框

MVC將列舉型別繫結到下拉框

專案中,有時候會遇到一些固定的選擇框的值,如果直接寫固定值,遇到好幾處用到的地方,到修改的時候比較麻煩。

可以將其存到資料庫中,也或者是存為列舉型別,修改也比較方便。

具體用法,列舉如下:

    /// <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等