gpt4 book ai didi

c# - 如何从 ViewBag 为 ASP.NET MVC DropDownList 设置默认值

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:07 24 4
gpt4 key购买 nike

在 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

关于c# - 如何从 ViewBag 为 ASP.NET MVC DropDownList 设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57399378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com