如何过滤枚举并在下拉菜单中使用它

时间:2017-04-17 08:36:05

标签: c# jquery linq enums

我是MVC 5的新手,我的目标是过滤我将在下拉列表中显示的enum中的列表

public enum DayofWeekType
{
      Monday=1,
      Tuesday= 2,
      Wednesday=3,
      Thursday=4,
      Friday= 5,
      Saturday=6,
      Sunday= 7
}

而我只是想在周五,周六和周日的下拉列表中显示当登录用户不是管理员时,我无法找到enum中过滤Model字段的解决方案,尝试在模型中添加条件但是总是总结出错误。尝试搜索LINQjQuery解决方案。

3 个答案:

答案 0 :(得分:2)

你可以这样做

   var enumlist =  Enum.GetValues(typeof(DayofWeekType)).Cast<DayofWeekType>().Select(v => new SelectListItem
    {
        Text = v.ToString(),
        Value = ((int)v).ToString()
    });

    if (IsUser) //your condition here
    {
      enumlist=  enumlist.Skip(4);

    }

    ViewBag.enumlist = enumlist;

并在您的视图中

@Html.DropDownListFor(x=>x.Id,(IEnumerable<SelectListItem>) ViewBag.enumlist)

.Skip会跳过前4个值,并以5thFriday

开头

答案 1 :(得分:0)

var weekValues = System.Enum.GetValues(typeof(DayofWeekType));
var weekNames = System.Enum.GetNames(typeof(DayofWeekType));

for (int i = 0; i <= weekNames.Length - 1 ; i++) {
    ListItem item = new ListItem(weekNames[i], weekValues[i]);
    ddlList.Items.Add(item);
}

答案 2 :(得分:0)

您必须在控制器级别过滤它,按照以下步骤实现

            int[] eliminateDays = null;
            // wrap enum into collection
            var enumDaysCollection = (from dayName in Enum.GetNames(typeof(DayofWeekType))
                                  select new
                                  {
                                      Text = dayName.ToString(),
                                      Value = (int)Enum.Parse(typeof(DayofWeekType), dayName)
                                  }).ToList();
            // array contain days (enum values) which will be ignored as per user specific
            // lets say you want to ignore monday, tuesday, wednesday, thursday 
            if (User.IsInRole("SomeUserRole"))
            {
                eliminateDays = new int[] { 1, 2, 3, 4 };
            }
            else if (User.IsInRole("AnotherUserRole"))
            {
                eliminateDays = new int[] { 1, 3 };
            }
            else
            {
                //For Admin will make empty so that it will show all days
                eliminateDays = new int[] { };
            }
            // filter collection
            var dropDownItems = (from day in enumDaysCollection
                                 let days = eliminateDays
                                 where !days.Contains(day.Value)
                                 select new SelectListItem
                                 {
                                     Text = day.Text,
                                     Value = Convert.ToString(day.Value)
                                 }).ToList();
            //send dropdownlist values to view
            ViewBag.DropDownItems = dropDownItems; 

最后将SelectListItem集合分配给下拉列表

@Html.DropDownList("DaysName", (List<SelectListItem>)ViewBag.DropDownItems, "Select Days..", new { @class = "dropdown" })