@Html.DropDownListFor(m => m.branch, CommonMethod.getBranch("",Model.branch), "--Select--", new { @multiple = "multiple" })
@Html.DropDownListFor(m => m.division, CommonMethod.getDivision(Model.branch,Model.division), "--Select--", new { @multiple = "multiple" })
I have two instances of DropDownListFor. I want to set selected as true for those which have previously stored values for Model.branch and Model.division. These are string arrays of stored ids
class CommonMethod
{
public static List<SelectListItem> getDivision(string [] branchid , string [] selected)
{
DBEntities db = new DBEntities();
List<SelectListItem> division = new List<SelectListItem>();
foreach (var b in branchid)
{
var bid = Convert.ToByte(b);
var div = (from d in db.Divisions where d.BranchID == bid select d).ToList();
foreach (var d in div)
{
division.Add(new SelectListItem { Selected = selected.Contains(d.DivisionID.ToString()), Text = d.Description, Value = d.DivisionID.ToString() });
}
}
}
return division;
}
}
The returned value of division is selected as true for the selected item in the model, but on view side it is not selected.
For me it works also for
@Html.DropDownListFor
:Model:
Controller:
Razor:
Submitted SelectedValues in controller looks like:
Use a
ListBoxFor
instead ofDropDownListFor
:The
branch
anddivision
properties must obviously be collections that will contain the selected values.And a full example of the proper way to build a multiple select dropdown using a view model:
that would be populated in the controller:
and in the view:
It is the HTML helper that will automatically preselect the items whose values match those of the
SelectedValues
property.