如何过滤枚举并在下拉列表中使用它

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

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

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

你可以这样做

  var enumlist = Enum.GetValues(typeof(DayofWeekType)).Cast().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) ViewBag.enumlist) 

.Skip将跳过前4值并从5th值开始,即Friday

 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); } 

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

  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)ViewBag.DropDownItems, "Select Days..", new { @class = "dropdown" })