MVC 利用枚举数据构造下拉框Select数据源

HTML页面:前台调用

<td class="round" uid="uid17">
                            <font>@item.PlanIntervalName</font>
                            <select id="PlanInterval" class="PlanInterval form-control" name="PlanInterval" style="display: none;" val="@item.PlanInterval">
                                @*<option value="0">实时推送</option>
                                <option value="1">每天推送一次</option>
                                <option value="2">每周推送一次</option>
                                <option value="3">每月推送一次</option>*@

                                @foreach (var i in ViewBag.PlanIntervalsList as List<SelectListItem>)
                                {
                                    if (item.PlanInterval == i.Value)
                                    {         
                                    <option value="@i.Value" selected="selected">@i.Text</option>
                                    }
                                    else
                                    {
                                    <option value="@i.Value">@i.Text</option>
                                    }
                                }
                            </select>
                        </td>

CS页面1:声明枚举

/// <summary>
        /// 时间间隔枚举
        /// </summary>
        public enum PlanIntervals
        {
            实时推送 = 0,
            每天推送一次 = 1,
            每周推送一次 = 2,
            每月推送一次 = 3
        }

CS页面2:将枚举数据转换为集合 SelectListItem

/// <summary>
        /// 把时间间隔枚举转换成数组 SelectListItem 
        /// </summary>
        /// <returns></returns>
        public static List<SelectListItem> PlanIntervalsSelectList()
        {
            List<SelectListItem> selectlist = new List<SelectListItem>();
            foreach (int i in Enum.GetValues(typeof(PlanIntervals)))
            {
                SelectListItem selectitem = new SelectListItem();
                selectitem.Value = i.ToString();
                selectitem.Text = Enum.GetName(typeof(PlanIntervals), i);
                selectlist.Add(selectitem);
            }
            return selectlist;
        }

CS页面3:后台调用

ViewBag.PlanIntervalsList = PlanIntervalsSelectList();    //任务类型下拉框数据源




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章