Removing an item from the drop-down list

I created a drop-down list so that users can choose which account they want to create by selecting a role. The problem I am facing is that it shows the administrator role in the drop down list. How would you hide or remove the administrator role from the list?

A drop-down list is created using the viewbag:

   public ActionResult Register()
        {
            List<SelectListItem> list = new List<SelectListItem>();
            SelectListItem item;
            foreach (String role in Roles.GetAllRoles())
            {
                item = new SelectListItem { Text = role, Value = role };
                list.Add(item);
            }

            ViewBag.roleList = (IEnumerable<SelectListItem>)list;
            return View();
        } 

Any advice - welcome

+3
source share
1 answer

Instead of removing the administrator role from the selection list, I think you should remove the administrator role from the array creating the selection list.

So instead

foreach (String role in Roles.GetAllRoles())


foreach (String role in Roles.GetAllRoles().Where(role => role != "admin"))

You could further annotate this limited role call in your own method, if you like.

, linq.

ViewBag.roleList = Roles.GetAllRoles().Where(role => role != "admin").
    Select(role => new SelectListItem { Text = role, Value = role}).ToList();

, SelectList .

+3

All Articles