在我的控制器中,我有:
var parentSubjects = new SelectList(_context.Subject, "SubjectId", "SubjectName");
parentSubjects.ToList().Insert(0, new SelectListItem() { Text = "None", Value = "" });
执行第二行时没有任何反应。我希望将空白项目插入列表中的第0个索引。我想念什么?
当您调用parentSubjects.ToList()
时,您正在从parentSubjects
创建列表的新副本,并且Insert
在该副本上进行操作。由于您没有保存列表,因此新项目会丢失。
您可以通过保存由ToList()
创建的列表并使用该列表来解决此问题:
var parentSubjects = new SelectList(_context.Subject, "SubjectId", "SubjectName").ToList();
parentSubjects.Insert(0, new SelectListItem() { Text = "None", Value = "" });
如果您在视图中使用asp-items
标记帮助器,则还有另一个选项可以避免必须为空白/默认选项创建SelectListItem
。您可以在此处将选项直接添加到HTML:
<select asp-for="SelectedSubjects" asp-items="Subjects">
<!-- simply add the option directly here; the options from
`asp-items` will be added below -->
<option value="">None</option>
</select>