我试图在调用
Edit
操作时在下拉列表中显示所选值。目前我的代码在下拉列表中显示以下内容。该值确实通过 @Html
方法 显示
@Html.EditorFor(model => model.Projectname)
但是我想要实现的是应该能够通过下拉列表带来所选值。我确实尝试将下拉列表存储在
ViewBag
中,但它显示 WebDSR.Models.DTO.Project
。
相反,它应该显示项目名称 - 所选数据库中的值
Amazon
Walmart
Myntra
控制器动作方法:
public IActionResult Edit(int id)
{
ViewBag.Project = new SelectList(db.Defects
.Where(x => x.DefectId == id)
.Select(x => new Project() { ProjectId = x.ProjectId, ProjectName = x.ProjectName}));
return View(db.Defects.Find(id));
}
查看
<select asp-items="ViewBag.Project" class="form-control"></select>
非常感谢任何帮助。
由于您提供的是模型类类型的
IEnumerable
列表而不是 IEnumerable<SelectListItem>
,因此您需要根据 SelectList(IEnumerable, String, String)
指定选项值和标签的属性名称。
ViewBag.Project = new SelectList(
db.Defects
.Where(x => x.DefectId == id)
.Select(x => new Project() { ProjectId = x.ProjectId, ProjectName = x.ProjectName }),
nameof(Project.ProjectId),
nameof(Project.ProjectName)
);
在 Razor 页面中,您缺少
@
来引用 ViewBag.Project
。
<select asp-items="@ViewBag.Project" class="form-control"></select>