gpt4 book ai didi

c# - ASP.NET MVC : DropDownListFor doesn't select any option

转载 作者:太空狗 更新时间:2023-10-29 23:18:57 25 4
gpt4 key购买 nike

我用它来填充 ASP.NET MVC View 中的下拉列表。

<%= Html.DropDownListFor(model => model.Bikes,
Model.Bikes.Select(
x => new SelectListItem {
Text = x.Name,
Value = Url.Action("Details", "Bike", new { bikeId = x.ID }),
Selected = x.ID == Model.ID,
})) %>

对此进行调试,我可以看到 Selected 属性在应该设置为 true 时设置为 true。但是当渲染 View 时,列表中的任何选项都没有被选中。我意识到这可以通过 DropDownListFor 的另一个重载来完成,但我真的想让这个版本工作。

有什么想法吗?

最佳答案

您选择的值不起作用的原因是因为您使用 Urls 作为选项值但指定了 Model.IDSelected子句。

像这样尝试:

<%= Html.DropDownListFor(
model => model.Bikes,
new SelectList(Model.Bikes, "Id", "Name", Model.ID)
)%>

"Id" "Name" 指示将用作选项值的属性指示将用作选项标签的属性。

如果你想保留Url.Action你可以试试:

<%= Html.DropDownListFor(
model => model.Bikes,
new SelectList(Model.Bikes.Select(x => new {
Id = x.Id,
Name = Url.Action("Details", "Bike", new { bikeId = x.ID })
}), "Id", "Name", Model.ID)
)%>

您会注意到我颠倒了 Name 和 Id,因为使用模型 Id 作为选项值似乎更符合逻辑。


更新:

这不起作用的原因是因为您绑定(bind)到 IEnumerable ( DropDownListFor 助手的第一个参数)。当您使用相同的 model.Bikes 时,它应该是一个标量属性收藏:

<%= Html.DropDownListFor(
model => model.SelectedBikeValue,
Model.Bikes.Select(
x => new SelectListItem {
Text = x.Name,
Value = Url.Action("Details", "Bike", new { bikeId = x.ID }),
Selected = x.ID == Model.ID,
}
)) %>

我关于不使用 Urls 作为选项值的评论是正确的。

关于c# - ASP.NET MVC : DropDownListFor doesn't select any option,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3352373/

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