In the view, I have
<div class="form-group">
<div>
@Html.LabelFor(m => m.DoctorList, new { @class = "control-label" })
</div>
<div>
@Html.ListBoxFor(m => m.DoctorList, new MultiSelectList((List<SelectListItem>)ViewBag.DoctorList, "Value", "Text", ((List<string>)(ViewBag.DoctorsSelected)).ToArray()), new {style="display:block;height:20.0em;", @class = "form-control", Multiple = "multiple"})
</div>
</div>
DoctorList is a list in model, ViewBag.DoctorList is the entire list of doctors, they are something similar to:
public static List<SelectListItem> GetDoctorList()
{
List<SelectListItem> ret = new List<SelectListItem>();
// load doctors from database
// for now, fake data
for (int k = 1; k <= 30; k++)
{
string n = "Doctor" + k.ToString();
ret.Add(new SelectListItem() { Value = n, Text = n });
}
return ret;
}
ViewBag.DoctorsSelected is a List, which is a list of doctor names, something similar to:
List<string> doctorsSelected = new List<string>();
doctorsSelected.Add("Doctor1");
doctorsSelected.Add("Doctor5");
What I want to do is that preselect the doctors in the listbox. However, it always shows the listbox, but no reselection.
I also tried to use below in GetDoctorList()
ret.Add(new SelectListItem() { Value = n, Text = n, Select = true });
Still no preselection.
Anyone knows how to do it? I'm using MVC4.
Thanks