Search code examples
c#asp.net-mvc-5selectlistoptgroupselectlistitem

How to make sure that selectlist items belong to the same SelectListGroup?


I am experimenting with the <optgroup> element and am trying to make several items belong to the same optgroup.

My code:

    public async Task<ActionResult> GetStatsView()
    {
        var users = await _administrationServiceAPI.GetPersons();
        var tanks = await _administrationServiceAPI.GetTanks();


        var list = new List<SelectListItem>();

        foreach (var u in users.Payload)
        {
            SelectListItem item = new SelectListItem {Text = u.Name, Value = u.Id.ToString(), Group = new SelectListGroup {Name = "Users"} };
            list.Add(item);
        }

        foreach (var u in tanks.Payload)
        {
            SelectListItem item = new SelectListItem { Text = u.Name, Value = u.Id.ToString(), Group = new SelectListGroup { Name = "Tanks" } };
            list.Add(item);
        }

        @ViewBag.MyList = list;

        return View("StatsView");
    }

view:

@Html.DropDownList("MyList")

result:

enter image description here

Desiered result is:

Users

UserName

UserName

UserName

Tanks

Tank

Tank

Tank

How do I do this?


Solution

  • To make it work, you need to reuse the SelectListGroup. Just use it like this:

        var usersGroup = new SelectListGroup {Name = "Users"};
        foreach (var u in users.Payload)
        {
            SelectListItem item = new SelectListItem {Text = u.Name, Value = u.Id.ToString(), Group = usersGroup };
            list.Add(item);
        }
    

    And of course similarly for Tanks.

    It does not matter that the name is the same, an instance used must be the same in various items to group them into single optgroup.