在我的MVC应用程序中,我正在检索基于ID
的对象列表,并通过SelectList将这些对象填充到Listbox中。这是我有的:
C#
ViewBag.SpecCatListBox = new SelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text");
HTML /剃刀
@Html.ListBoxFor(model => model.LstSpecialCategories, (SelectList)ViewBag.SpecCatListBox, new { id = "SpecialCat-ListBox", @class = "form-control" })
在页面加载时,列表框中填充了正确的选项,但它们未被选中。有没有办法在没有循环的情况下做到这一点(这是我在其他帖子中看到的)?
任何帮助表示赞赏。
UPDATE
我编辑了一些内容,并添加了一行代码。
C#
ViewBag.SpecCatListBox = new SelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text", SelectListMethods.LstChosenSpecCat(incidentVm.ID));
ViewBag.SpecCatIds = db.TBL_AssocIncidentSpecialCat.Where(x => x.IncidentId == incidentVm.ID)
.Select(x => x.SpecialCategoriesId).ToList();
HTML /剃刀
@Html.ListBoxFor(model => model.LstSpecialCategories, new MultiSelectList(ViewBag.SpecCatListBox, "Value", "Text", ViewBag.SpecCatIds), new { id = "SpecialCat-ListBox", @class = "form-control" })
这是根据需要选择所有选项,但有没有办法不使用2个Viewbag对象?
我已经想到了这一点。
C#
ViewBag.SpecCatListBox = new MultiSelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text", SelectListMethods.LstChosenSpecCat(incidentVm.ID).Select(x => x.Value));
HTML /剃刀
@Html.ListBoxFor(model => model.LstSpecialCategories, (MultiSelectList)ViewBag.SpecCatListBox, new { id = "SpecialCat-ListBox", @class = "form-control" })