Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Populate ListBoxFor in Mvc3?

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.

like image 659
Rachit Avatar asked Apr 05 '12 12:04

Rachit


2 Answers

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

like image 123
Azadrum Avatar answered Jan 02 '23 17:01

Azadrum


@ 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 view, bind the viewdata like,

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

For testing, try a sample selectlist item 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, then check your function "_supp.listDocImages()" and make sure it return IList

like image 35
Rifaj Avatar answered Jan 02 '23 16:01

Rifaj