whiteproud
whiteproud

Reputation: 95

How to display multi-select list from List<MyObject>

class User() {
   public List<Customer> Customers;
}

class Customer() {
   public long Id;
   public string Name;
}

I populate the selected items

User MyUser = new User(); 
MyUser.Customers = db.Customers.Where(...).ToList();

I pass the list of all items in this way

ViewBag.Customers = db.Customers.OrderBy(c => c.Name).ToList();

In my View i want to display it like a multi-select HTML element with all (ViewBag.Customers) elements and (MyUser.Customers) as selected. I tried with

@model MySCL.Models.User

@Html.ListBoxFor(m => m.Customers, new MultiSelectList(ViewBag.Customers, "Id", "Name"), new {Multiple = "multiple", size = "5" })

but it display only the complete list without select any items. Is this the best practice to do it? Is there another better way? Instead of a List of Customer if I had a List of string how can I do it?

Upvotes: 4

Views: 3703

Answers (2)

whiteproud
whiteproud

Reputation: 95

I resolved by passing the 4th parameter as a list of int or string with the only key of the objects and not a list of objects.

new MultiSelectList(ViewBag.Customers, "Id", "Name", Model.Customers.Select(c => c.Id))

Upvotes: 1

Jason Berkan
Jason Berkan

Reputation: 8884

The MultiSelectList constructor also takes an IEnumerable list of items to be selected, so if you change your code to:

new MultiSelectList(ViewBag.Customers, "Id", "Name", Model.Customers)

The list should then start with all the customer's items selected.

Upvotes: 1

Related Questions