views:

594

answers:

3

Hi

I am trying to re-select items in a listbox with asp.net mvc

Html.ListBox("SupplierId",
             new SelectList(Model.Suppliers, "Id", "Name", Model.SelectedSuppliers))

Here is the viewdata

var viewData = new ViewData.SubstrateEditViewData(
               new DataAccess.SubstrateRepository().GetItemById(id),
               new DataAccess.SupplierRepository().GetItems(),
               new DataAccess.SupplierSubstrateRepository().GetItems().Where(s =>  s.SubstrateId ==id).Select(s => s.Supplier));

for some reason its not selected the items even tho I can see the Model.SelectedSupplier containing two Supplier objects.

Thanks

A: 

The documentation for the SelectList constructor refers to a single value. It does't look like passing in a List or IEnumerable of values will result in a listbox with multiple values selected.

Anthony Conyers
I have changed to MultiSelectList
Still no luck will try some more variants
Html.ListBox("SupplierId", new MultiSelectList(Model.Suppliers, "Id", "Name", Model.Suppliers)) should in theory select all the items. But it does not
A: 

I struggled with the same problem a few weeks ago. The default extension methods for MultiSelect lists do not behave as expected. I ended up just looping through the items myself and setting their selected property manually.

çağdaş
+2  A: 

Note what only ids of items should be passed to selectedValues parameter of MultiSelectList() method so you should use

Html.ListBox("SupplierId", new MultiSelectList(Model.Suppliers, "Id", "Name",
    Model.SelectedSuppliers.Select(s => s.Id)))
Alexander Prokofyev
Thanks, this sorted me out.
Richard