Our task was simple as changing DropDownListFor into ListBoxFor. It does not return any errors on compile time when you just change DropDownListFor into ListBoxFor. But it is not that simple.
We did use MultiSelectLists to populate our DropDownList and it was working just fine until we decided to change it into ListBoxFor. Then we thought that there is something that we have missed. Our DropDownListFor was in the following format,
<%:Html.DropDownListFor(
x => x.ContacId,
new
MultiSelectList(Model.Contacts, "ContactId", "ContactName"))%>
It is just a simple dropdown, which have element id as ContactId, and text as ContactName. The populating IEnumerable was Model.Contacts. So far it is just fine and working well.
Then we need to change this into ListBoxFor since user needs to select multiple elements and dropdown component is just not enough for it.
When you just change dropdown into listbox it seems fine until you run the page. We got source is null error and at first glance did not have any idea about it. After some google searches we found a solution which simply indicates that listboxfor needs selected element list as first argument not id of select list (in this case it is ContactId).
We modified our model with a new list which just contains selected items in listboxfor. So our listboxfor turned into following,
<%:Html.ListBoxFor(
x => x.SelectedContacts,
new
MultiSelectList(Model.Contacts, "ContactId", "ContactName"))%>
You have to simply indicate selected items as a list since it has the ability to select multiple items.
Hope it helps,
Have a nice day.
Mehmet
No comments:
Post a Comment