How to Populate ListBoxFor in Mvc3?

Rachit picture Rachit · Apr 5, 2012 · Viewed 20.4k times · Source

I have a list of type stored procedure which have an ID and a Name as data in it. i have property of int type in model and a list of same stored procedure. now i want to bind this information into ListBoxFor

in view i have written this

@Html.ListBoxFor(x => x.HobbyId, new MultiSelectList(Model.listHobby, "pkHobbyId", "Hobby"))

but i am getting an error

The parameter 'expression' must evaluate to an IEnumerable when multiple selection is allowed.

Please Help how to bind.

Answer

Azadrum picture Azadrum · Apr 5, 2012

try that

@Html.ListBoxFor(x => x.HobbyId, Model.listHobby.Select(f => new SelectListItem { Text = f.Hobby, Value = f.pkHobbyId.ToString() }), new { Multiple = "multiple" }) 

listHobby is iEnumerable list on my sample


sorry if i mislead you, rushed to answer but you cannot get the result of the multiselect listbox into a guid or int variable (whatever type is your HoobyId is) you should have an array to grab the result like

public string[] SelectedHobbyIds { get; set; }

so there must be something wrong with your View Models so its better that u would post your view models to be checked