在我的MVC应用程序中,我正在基于ID
检索对象列表,并将这些对象通过SelectList填充到列表框中。这是我所拥有的:
C#
ViewBag.SpecCatListBox = new SelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text");
HTML / Razor
@Html.ListBoxFor(model => model.LstSpecialCategories, (SelectList)ViewBag.SpecCatListBox, new { id = "SpecialCat-ListBox", @class = "form-control" })
在页面加载时,列表框将填充正确的选项,但未选中它们。有没有一种方法可以不循环(这是我在其他帖子中看到的)?
感谢您的帮助。
更新
我已经编辑了一些内容,并添加了一行代码。
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 / Razor
@Html.ListBoxFor(model => model.LstSpecialCategories, new MultiSelectList(ViewBag.SpecCatListBox, "Value", "Text", ViewBag.SpecCatIds), new { id = "SpecialCat-ListBox", @class = "form-control" })
这是根据需要选择所有选项,但是有没有办法不使用2个Viewbag对象?
答案 0 :(得分:1)
我已经弄清楚了。
C#
ViewBag.SpecCatListBox = new MultiSelectList(SelectListMethods.LstChosenSpecCat(incidentVm.ID), "Value", "Text", SelectListMethods.LstChosenSpecCat(incidentVm.ID).Select(x => x.Value));
HTML / Razor
@Html.ListBoxFor(model => model.LstSpecialCategories, (MultiSelectList)ViewBag.SpecCatListBox, new { id = "SpecialCat-ListBox", @class = "form-control" })