asp.net mvc - Unable to display MultiSelectList.SelectedValues on MVC view -
i working mvc
application legacy code. far, changes made 2 calls retrieve lists of accountdivisionmodel
objects. original code called stored procedures , returned objectresult
, contained data.
public class accountdivisionmodel { int divisionid; string divisionname; int accountid; bool isactive; }
i'm making 2 calls retrieve list of divisions belong account , list of (selected) divisions belong contact of account.
var adivs = account.getdivisionbyaccountid(c.accountid).toarray(); var cdivs = contact.getdivisionbycontactid(c.contactid).toarray(); viewbag.accountdivisions = new multiselectlist(adivs, "divisionid", "divisionname", cdivs);
in edit view
@html.dropdownlist("accountdivisions", null, htmlattributes: new { @class = "form-control", @multiple = "multiple", @placeholder = "select division(s)" })
i don't know why selectedvalues
not showing though when click on text box (@placeholder), can see populate drop down list divisions.
what have done wrong?
below image of current working interface. can see, selected values displayed in box , drop down list showing remaining items have not been selected.
the 4th argument of multiselectlist
needs collection of selected values (usually int
or string
) match type of second parameter. passing collection of complex objects not match option value. solve changing
var cdivs = contact.getdivisionbycontactid(c.contactid).toarray();
to
var cdivs = contact.getdivisionbycontactid(c.contactid).select(c => c.divisionids);
however recommend including property in model representing selected divisions allows 2 way binding
model
public ienumerable<int> selecteddivisions { get; set; }
controller
model.selecteddivisions = contact.getdivisionbycontactid(c.contactid).select(c => c.divisionid); viewbag.accountdivisions = new multiselectlist(adivs, "divisionid", "divisionname"); // 4th parameter not required
view
@html.listboxfor(m => m.selecteddivisions, (multiselectlist)viewbag.accountdivisions, new { @class = "form-control"}) // listboxfor adds multiple attribute
the model contains selected values on post back.
Comments
Post a Comment