.net 带有SelectListGroup的SelectList

m1m5dgzv  于 2023-06-25  发布在  .NET
关注(0)|答案(2)|浏览(115)

我试图使用SelectListGroup返回一个SelectList<optgroup>的值,但下面的代码只返回SelectList中的值,而不包括组。如何将我的选择列表按组分隔?

public SelectList MyList()
{
   var group1 = new SelectListGroup() { Name = "Group 1" };
   var group2 = new SelectListGroup() { Name = "Group 2" };

   var items = new List<SelectListItem>();

   items.Add(new SelectListItem() { Value = "1", Text = "Item 1", Group = group1 });
   items.Add(new SelectListItem() { Value = "2", Text = "Item 2", Group = group2 });

   return new SelectList(items, "Value", "Text");
}
ukxgm1gy

ukxgm1gy1#

我发现这个方法是有效的,它使用了一种强类型的方法:

查看模型:

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

实体模型示例(本例):

public class Entity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    public bool IsDefault { get; set; }
}

控制器:

// Get list for the dropdown (this uses db values)
var entityList = db.Entity.ToList();

// Define the Groups
var group1 = new SelectListGroup { Name = "Active" };
var group2 = new SelectListGroup { Name = "Allowed" };

// 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(entityList.Select(item => new SelectListItem
{
    Text = item.Name,
    Value = item.Id,
    // Assign the Group to the item by some appropriate selection method
    Group = item.IsActive ? 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 = entityList.FirstOrDefault(a => a.IsDefault).Id,
    DropdownList =  dropdownList
};

浏览次数:

<!-- If needed, change 'null' to "Please select item" -->
@Html.DropDownListFor(a => a.SelectedDropdownItem, Model.DropdownList, null, new { @class = "some-class" })

希望它能帮助到某人。

w1jd8yoj

w1jd8yoj2#

如果你有动态组,你必须使用'foreach',因为SelectListGroup正在使用引用。

foreach (var group in groups)
{
   foreach (var item in items.Where(i => i.Group == group))
   {
      var selectItem = new SelectListItem
      {
         Name = item.Name,
         Value = item.Value,
         Group = group
      };
   }
}

相关问题