How can I add option groups in ASP.NET drop down list?

后端 未结 10 1175
遇见更好的自我
遇见更好的自我 2020-11-28 10:22

I have a requirement of grouping the drop down list options in ASP.NET drop down server control. Do you have any idea to how to approach the issue? I am new to ASP.NET.

10条回答
  •  萌比男神i
    2020-11-28 11:12

    I use this method, which avoids ViewBag and ViewData:

    View model:

    public class PageViewModel
    {
        public int SelectedDropdownItem { get; set; }
        public IEnumerable DropdownList { get; set; }
    }
    

    Example entity model (for this example):

    public class Users
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsAdministrator { get; set; }
        public bool IsDefault { get; set; }
    }
    

    Controller:

    // Get list for the dropdown (this uses db values)
    var userList = db.Users.ToList();
    
    // Define the Groups
    var group1 = new SelectListGroup { Name = "Administrators" };
    var group2 = new SelectListGroup { Name = "Users" };
    
    // Note - the -1 is needed at the end of this - pre-selected value is determined further down
    // Note .OrderBy() determines the order in which the groups are displayed in the dropdown
    var dropdownList = new SelectList(userList.Select(item => new SelectListItem
    {
        Text = item.Name,
        Value = item.Id,
        // Assign the Group to the item by some appropriate selection method
        Group = item.IsAdministrator ? group1 : group2
    }).OrderBy(a => a.Group.Name).ToList(), "Value", "Text", "Group.Name", -1);
    
    // Assign values to ViewModel
    var viewModel = new PageViewModel
    {
        // Assign the pre-selected dropdown value by appropriate selction method (if needed)
        SelectedDropdownItem = userList.FirstOrDefault(a => a.IsDefault).Id,
        DropdownList =  dropdownList
    };
    

    View:

    
    @Html.DropDownListFor(a => a.SelectedDropdownItem, Model.DropdownList, null, new { @class = "some-class" })
    

    Hope this helps someone to avoid what happened to me - way too much time spent finding a strongly-typed method.

提交回复
热议问题