2

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;
tereško
  • 58,060
  • 25
  • 98
  • 150
Roman
  • 97
  • 9
  • The question is reversed from what you posted as your actual error message. It's unable to convert String to SelectListItem. – Aaron Palmer Dec 06 '13 at 17:30
  • If I'm understanding your issue correct, you just need to properly bind your ListBox to your model and you shouldn't need two. Check this question: http://stackoverflow.com/questions/11935106/binding-listbox-with-a-model-in-mvc3 – Aaron Palmer Dec 06 '13 at 17:41

1 Answers1

2

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"})  
Réda Mattar
  • 4,361
  • 1
  • 18
  • 19