How to populate ListBoxFor in Mvc3?

I have a list of type stored procedures that have an ID and a name as data. I have a property of type int in the model and a list of the same stored procedure. now I want to associate this information with ListBoxFor

i wrote this

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

but i get an error

The 'expression' parameter must be evaluated in IEnumerable if multiple selection is enabled.

Please help how to tie.

+7
source share
3 answers

try

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

listHobby is an iEnumerable list in my example


Sorry, if I misled you, I hastened to answer, but you cannot get the result of a multi-selector list in the guid or int variable (whatever type your HoobyId may be), you must have an array to get the result, for example

 public string[] SelectedHobbyIds { get; set; } 

therefore, there should be something wrong with your view models, so it’s better that you publish your view models that will be tested.

+7
source

@Chhatrapati Sharma,

In your controller, try this,

 ViewData['anyName'] = new SelectList { Text = , // text from ur function Value = , // Value from function Selected = // if required } 

and, in this regard, link viewdata as,

  <@Html.ListBox("docImages", ((IEnumerable<SelectListItem>)ViewData["anyName"])) 

For testing, try selecting the selectlist element as follows:

 ViewData['anyName'] = new List<SelectListItem>{ new SelectListItem {Text = "First", Value = "0"}, new SelectListItem {Text = "Second"), Value = "1"}, new SelectListItem {Text = "Third", Value = "2"} }; 

If this sample works, check your function "_supp.listDocImages ()" and make sure it returns an IList

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

HobbyId in the expression must be ienumerable because you set multi select

+3
source

All Articles