如何在 ASP.NET Core MVC 中设置 Html.DropDownList 的值

问题描述 投票:0回答:0

我正在编辑表单,我无法根据模型值设置

Html.DropDownList
中显示的值。

这是我目前所拥有的:

@Html.DropDownList("OrgId", 
                   (IEnumerable<SelectListItem>)ViewBag.orgList, 
                   Model.ShortName, 
                   new { @class = "form-select", @style="width:120px"})

加载表单时,它确实具有与模型对应的正确

ShortName
,但是当提交表单时,与
ShortName
相关联的索引为0而不是
Id
。它只是在列表顶部添加
ShortName
,而不是将其设置为列表中的正确索引。

在控制器中

ViewBag.orgList
被设置为:

ViewBag.orgList = new SelectList(_context.Organizations
                                         .Where(x => x.Id != 0)
                                         .OrderBy(p => p.ShortName), 
                                 "Id", "ShortName");

也许我应该使用

DropDownListFor
但我是 ASP.NET Core MVC 的新手,不知道哪个是最好的选择。

有人可以指出我正确的方向吗?

asp.net-core-mvc dropdownlistfor
© www.soinside.com 2019 - 2024. All rights reserved.