我在我的控制器中使用此方法向ViewBag添加一些列表,该列表由两个操作使用:Create
和Edit
。列表已正确设置,某些项目已将Selected
属性设置为true。
private void AddUsersAndTrucksListsToViewBag(string[] selectedUsers, int[] selectedTrucks)
{
ViewBag.UsersList = uow.UsersRepository
.GetAll(_siteId)
.Where(u => u.IsActive)
.Select(u => new SelectListItem()
{
Value = u.Id,
Text = $"{u.Name} {u.Surname}",
Selected = selectedUsers != null && selectedUsers.Contains(u.Id)
})
.ToArray();
ViewBag.TrucksList = uow.OspRepository
.GetAllTrucks(_siteId)
.Select(t => new SelectListItem()
{
Value = t.Id.ToString(),
Text = $"{t.Codename} {t.Manufacturer} {t.Model}",
Selected = selectedTrucks != null && selectedTrucks.Contains(t.Id)
})
.ToArray();
}
在Edit
视图中:
<div class="form-group">
@Html.Label("Osoby", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.SelectedUserIds, (SelectListItem[])ViewBag.UsersList, new { @class = "form-control", multiple = "multiple" })
</div>
</div>
<div class="form-group">
@Html.Label("Samochody", htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.DropDownListFor(model => model.SelectedTruckIds, (SelectListItem[]) ViewBag.TrucksList, new {@class = "form-control", multiple = "multiple"})
</div>
</div>
在Create
视图中完全相同:
<div class="form-group">
@Html.Label("Osoby", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.SelectedUserIds, (SelectListItem[])ViewBag.UsersList, new { @class = "form-control ", multiple = "multiple" })
</div>
</div>
<div class="form-group">
@Html.Label("Samochody", htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.DropDownListFor(model => model.SelectedTruckIds, (SelectListItem[]) ViewBag.TrucksList, new {@class = "form-control ", multiple = "multiple"})
</div>
</div>
问题是在Edit
视图中一切正常。但在Create
视图中,只有第二个列表正确呈现了selected
HTML属性。这可以在截图
这有什么问题?我发现它可能是由于ViewBag
属性名称与某些Model
属性名称相同,但它不是。
两个列表都有multiple
属性。
这是由ListBoxFor()
<select class="form-control " id="SelectedUserIds" multiple="multiple" name="SelectedUserIds">
<option value="525b1890-942f-4fb4-96de-56e04b6ca196">Jan Kowalski</option>
<option value="5b0e1c01-0e46-436c-aa9b-ac63e66d691f">Adam Pawlak</option>
</select>
<select class="form-control " id="SelectedTruckIds" multiple="multiple" name="SelectedTruckIds">
<option selected="selected" value="3">425[O]21 MAN 12.232</option>
</select>