Why is ListBoxFor not selecting items, but ListBox is?

I’ve stumbled across this problem myself, finally I realized that the problem was a naming convention.

You cannot name the ViewBag or ViewData poperty containing the SelectList or MultiSelectList to the same name your property model containing the selected items. At least not if you’re using the ListBoxFor or DropDownListFor helper.

Here’s an example:

    public class Person
          public List<int> Cars { get; set; }

    public ActionResult Create()
          //wont work
          ViewBag.Cars = new SelectList(carsList, "CarId", "Name"); 

          //will work due to different name than the property.
          ViewBag.CarsList = new SelectList(carsList, "CarId", "Name"); 

          return View();

    @Html.ListBoxFor(model => model.Cars, ViewBag.CarsList as SelectList)

I’m sure theres plenty of other ways doing this, but it solved my problem, hope it will help someone!

Leave a Comment