MVC 5 Razor - Listbox that displays items passed in a Viewbag list
10,966
Solution 1
You need to specify the display member and value member that will be used to render the string representation of the object, otherwise MVC will just call ToString
.
SelectList
has an overloaded constructor for this e.g.:
new SelectList(items, "ValuePropertyName", "DisplayPropertyName")
see here:
Solution 2
you can use MultiSelectList some thing like that In Action
ViewBag.lstMembers = new MultiSelectList(db.ClubMembers.ToList(), "ValueProperty", "NameProperty");
in View
@Html.ListBox("lstMembers", ViewBag.lstMembers as MultiSelectList)
Author by
Cathal O 'Donnell
Updated on June 04, 2022Comments
-
Cathal O 'Donnell almost 2 years
I am passing a ViewBag list to my view and I am trying to display this list in a listbox so as I can select items of this list.
This is the controller method for the view:
public ActionResult AddMembers(int? id) { ViewBag.lstMembers = db.ClubMembers.ToList(); var selClub = db.Clubs.Find(id); if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } return View(selClub); }
This is what I have currently but it is not displaying the items correctly as shown in the photo below:
@Html.ListBoxFor(m => m.ClubMembers, new SelectList ( ViewBag.lstMembers))
How can I set the source of my listbox so that it will display the items passed in via the ViewBag.lstMembers from the controller method