Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing item from dropdown list

I have created a dropdown list to let users select which account they wish to create by selecting a role. The problem I am facing is that it shows the admin role in the dropdown. How would you go about hiding or removing the admin role from the list?

The dropdown list is generated with a 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

like image 876
Daza Aza Avatar asked Dec 05 '25 02:12

Daza Aza


1 Answers

Rather than removing the admin role from the select list, I think you should instead remove the admin role from the array that's creating the select list.

So instead of

foreach (String role in Roles.GetAllRoles())


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

You could further abstract this limited role call into its own method if you wished.

Not part of your question, but you could replace all of that code with a simple linq statement.

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

Also not part of your question, but I'd highly recommend making the SelectList part of your viewmodel.

like image 194
DMulligan Avatar answered Dec 07 '25 02:12

DMulligan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!