I can't really explain why, but I managed to get it working. Either of these worked:
@Html.ListBoxFor(m => m.SelectedFoos,
new MultiSelectList(Model.AllFoos, "ID", "Name"), new {Multiple = "multiple"})
@Html.ListBoxFor(m => m.SelectedFoos, Model.AllFoos
.Select(f => new SelectListItem { Text = f.Name, Value = f.ID }),
new {Multiple = "multiple"})
The problem seems to be that the Selected property on SelectListItem is ignored, and instead the ToString()
(!) method is being called, so if you need to add this to your Foo
class:
public override string ToString()
{
return this.ID;
}
I'm guessing it has something to do with being able to persist across requests (which will be flattened to strings to be passed over the wire), but it's a bit confusing!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…