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:

https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist.selectlist(v=vs.118).aspx#M:System.Web.Mvc.SelectList.

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)
Share:
10,966
Cathal O 'Donnell
Author by

Cathal O 'Donnell

Updated on June 04, 2022

Comments

  • Cathal O 'Donnell
    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))
    

    enter image description here

    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