How to display a list with multiple lists from the <MyObject> list

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

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

I fill in the selected items

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

I pass a list of all the elements in this way

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

In my view, I want to display it as an element with several HTML elements with all the elements (ViewBag.Customers) and (MyUser.Customers) selected. I tried using

@model MySCL.Models.User

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

but it only displays the complete list without selecting any items. Is this the best practice? Is there any better way? Instead of a list of clients, if I had a list of strings, how can I do this?

+5
source share
2 answers

The MultiSelectList constructor also accepts a list of IEnumerable elements to choose, so if you change your code to:

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

.

+1

4- int string , .

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

All Articles