I'm trying to create a listbox with multiple selected items but it doesn't work.

 

My model:

Model with many to many relationship

 

Function Edit(ByVal id As Integer) As ActionResult
 Dim vm As New ViewModels.NewsItemViewModel() With {
  .NewsItem = _
db.NewsItems.Include("NewsCategories").Single(Function(item) item.Id = id),
  .Categories = _
New MultiSelectList(db.Categories, "Id", "Category", .NewsItem.NewsCategories)
 }
 Return View(vm)
End Function

The first param of MultiSelectList is the list of Categories, the last param is the list of selected categories.

 

It doesn't work because nothing gets selected

<select id="NewsItem_NewsCategories" 
multiple="multiple" name="NewsItem.NewsCategories">
<option value="1">Politics</option>
<option value="2">Economy</option>
<option value="3">Sports</option>
</select>

 

Then I read somewhere that the last param expects a list of strings with the ids. So I modified my code

Function Edit(ByVal id As Integer) As ActionResult
 Dim vm As New ViewModels.NewsItemViewModel() With {
  .NewsItem = _
db.NewsItems.Include("NewsCategories").Single(Function(item) item.Id = id),
  .Categories = _
New MultiSelectList(db.Categories, "Id", "Category", .NewsItem.NewsCategories.Select(Function(c) c.id.ToString())
 }
 Return View(vm)
End Function

 

When I looked up the values during runtime I got some hope:

 

But the resulting HTML is the same as what I showed in my first html sample: nothing is selected.

 

Since the MVC code is open source you can view MultiSelectList's code: download here.