I was trying to populate a drop down list in a view which led me to:
ASP.NET MVC DropDownListFor with model of type List<string>
The solution out there works well. So now I have a “Create new project” view that takes in a “Project” model, and my model has, among other things:
public int projectPrimaryEmployeeID
{
get
{ return _projectPrimaryEmployeeID; }
set
{
_projectPrimaryEmployeeID = value;
}
}
public IEnumerable<SelectListItem> employeeList { get; set; }
In my GET action result, I am populating the employeeList with items from the database, and the drop down populates fine.
But now I have a view that enumerates over my model (a listing of all projects) and for each project, I need to display the pull down showing the list of employees over and over..
My “Show all projects” view has:
@model IEnumerable<MVCCodeProject.Models.project>
..in which I am saying:
@Html.DropDownListFor(modelItem => item.projectPrimaryEmployeeID, new SelectList(Model.employeeList, "Value", "Text"))
But I get an error:
'System.Collections.Generic.IEnumerable<MVCCodeProject.Models.project>' does not contain a definition for 'employeeList' and no extension method 'employeeList' accepting a first argument of type 'System.Collections.Generic.IEnumerable<MVCCodeProject.Models.project>' could be found (are you missing a using directive or an assembly reference?)
So seems like while enumerating over the model, the route to take to display the pull downs is probably a little different, any help?
So first you’ll need to change the model to IList:
And then you’ll be able to iterate of the list and bind to each item in that list by using the index:
There are also other strategies to do this, like using templates. Read more about it here: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx