我覺得這個方法可行,它使用一個強類型的方法:
視圖模型:
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" })
希望它可以幫助別人。
你可以用組創建'List',但是通過創建並返回一個新的'SelectList'將其扔掉。將該方法更改爲'public List MyList()'和'return items;' –
感謝您的幫助。它仍然不會在列表中顯示我的組。 – user2531854
這應該可以正常工作。實際發生了什麼,以及您如何在視圖中使用它? –