我正在使用ViewBag填充下拉列表。在编辑页面中,我的Dropdown属性具有值,并且不能为空。但我遇到错误“可为空的对象必须具有值”。在“ @foreach(ViewBag.Designations中的可变项)”行中。我尝试在视图中使用HtmlHelper和普通循环。
//控制器
int orgId = Convert.ToInt32(Session["OrganisationId"]);
ViewBag.Designations = db.Designations.Where(r => r.OrganisationId ==orgId).ToList();
//查看
<select class="custom-select select2 select2-hidden-accessible" tabindex="-1" aria-hidden="true" id="DesignationId" name="DesignationId">
<option value="">Select Designation</option>
@foreach (var item in ViewBag.Designations)
{
if (item.DesignationId == Model.DesignationId)
{
<option value="@item.DesignationId" selected>@item.DesignationName</option>
}
else
{
<option value="@item.DesignationId">@item.DesignationName</option>
}
}
</select>
//我也尝试过
@Html.DropDownListFor(model => model.DesignationId, new SelectList(ViewBag.Designations, "DesignationId", "DesignationName"), htmlAttributes: new { @class = "custom-select select2 select2-hidden-accessible", id = "DesignationId" })