简体   繁体   中英

How to Filter Enum and Use it in Dropdown

I am new to MVC 5 and My goal is to filter the list in my enum that I will show in my dropdown list

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

And I just want to show is friday,saturday and sunday in dropdown when the logged user is Not Administrator, I cant find solution on filtering enum field in Model , tried adding Conditions in model but always sums up with errors. Tried searching for LINQ and jQuery solutions.

you can do it like this

   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;

and in your view

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

.Skip will skip first 4 values and start with 5th value which is 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);
}

You have to filter it at controller level follow the below steps to achieve

            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; 

And finally assign SelectListItem collection to dropdownlist

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM