I\'m incredibly confused, because this seems like it should be simple but I can\'t get my ListBox
to be populated with selected values. I\'ve looked at several
You cannot bind a <select>
element to a collection of complex objects. A multiple select only posts back an array of simple values - the values of the selected options.
Your model needs to be
public class ItemViewModel
{
public IEnumerable<Item> AllItems { get; set; }
public IEnumerable<int> SelectedItems { get; set; }
}
and in the controller
SelectedItems = new List<int>(){ 1 }
then using
@Html.ListBoxFor(m => m.SelectedItems, new SelectList(Model.AllItems, "Id", "Name")
will select the first option in the dropdownlist.
Note that the ListBoxFor()
method sets multiple="multiple"
so there is no need to set it again. In addition, Setting the last parameter of in the SelectList()
(or MultiSelectList()
) constructor is pointless. Its the value of the property your binding to which determines what is selected and internally the ListBoxFor()
method ignores that parameter.
I would also suggest your property should be
public IEnumerable<SelectListItem> AllItems { get; set; }
so that you can simply use
@Html.ListBoxFor(m => m.SelectedItems, Model.AllItems)