Reputation: 5943
In my MVC application, I am retrieving a list of objects based on an ID
and stuffing those objects into a Listbox via a SelectList. Here is what I have:
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" })
On page load, the listbox is filled with the correct options, except that they're not selected. Is there a way to do this without looping (which is what I've seen in other posts)?
Any help is appreciated.
UPDATE
I've edited a few things, along with added a line of code.
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" })
This is selecting all of the options as needed, but is there a way to not use 2 Viewbag objects?
Upvotes: 0
Views: 433
Reputation: 5943
I have figured this out.
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" })
Upvotes: 1