在 Controller 索引中,我有以下内容:
ViewBag.Assignees = (await GetAllUsers()).Select(a =>
new SelectListItem
{
Text = a.DisplayName,
Value = a.Username,
Selected = a.DisplayName == "John Smith"
}).OrderBy(x => x.Text).ToList();
在 View 中,我有以下内容:
@Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", @class = "form-control"})
下拉列表按预期填充,但是,确实存在的默认 (selected = true) 值未设置。有人可以告诉我上面有什么问题吗?
更新:
通过将 SelectListItem.Value
更改为 a.DisplayName
(与 SelectedListItem.Text
相同)我实现了它。仍然不确定是什么阻止了下拉列表显示带有 Selected = true
的项目
如果 model.Assignee
带有值,并且如果它是一个 int,它将默认为 0,它将覆盖 SelectListItem 选定的值。
我建议设置model.Assignee
。
我是一名优秀的程序员,十分优秀!