So I have 2 ListBox controls one is filled with options the other one is empty. The point is when I submit the form I can see which values they have selected from the second ListBox. But when is posts the modelstate is invalid with this error for one of these values:
{"The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types."} for that
html:
@Html.ListBoxFor( x => x.RolesAvailable, new MultiSelectList(Model.RolesAvailable, "Value", "Text", Model.RolesAvailable),
new {Multiple = "multiple"}
)
@Html.ListBoxFor( x => x.RolesSelected, new MultiSelectList(Model.RolesSelected, "Value", "Text", Model.RolesSelected),
new { Multiple = "multiple" }
)
model:
public IEnumerable<SelectListItem> RolesAvailable { get; set; }
public IEnumerable<SelectListItem> RolesSelected { get; set; }
controller (avm is my viewmodel):
List<SelectListItem> sRoles = new List<SelectListItem>();
foreach (SelectListItem SI in avm.RoleListItems)
{
sRoles.Add(SI);
}
avm.RolesAvailable = sRoles;
List<SelectListItem> items = new List<SelectListItem>();
avm.RolesSelected = items;
When you write @Html.ListBoxFor( x => x.RolesSelected
..., it means that RolesSelected
contains selected values, those selected values are a collection of the same type as your Value
property. If your options' values are integers, the collection used for @Html.ListBoxFor( x => x.MySelectedValues
... must be an IEnumerable<int>
.
You should make two separate collections in your view model : an IEnumerable<SelectListItem>
used to build your ListBox, and an IEnumerable<*MyValueType*>
used to get your selected values, if the Value
property is a value type or a string.
Also, the 4th parameter used in your new MultiSelectList
is also a collection of selected values :
@Html.ListBoxFor(x => x.SelectedRoles,
new MultiSelectList(Model.RolesAvailable, "Value", "Text", Model.SelectedRoles),
new {Multiple = "multiple"})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments