New to MVC trying to populate a dropdown from Database, proving a bit more tricky than I imagined.
Here's what I have.
public class EmployeeDetailsModel
{
public string SelectedEmployee { get; set; }
public IEnumerable<SelectListItem> Employees { get; set; }
}
Controller
public ActionResult MiEmployeeDetails()
{
var model = new EmployeeDetailsModel();
model.Employees = _db.geo_employees.ToList().Select(x => new SelectListItem
{
Value = x.name,
Text = x.name
});
return View(model);
}
View
<%= Html.DropDownListFor(x => x.SelectedEmployee, (SelectList) Model.Employees) %>
But getting the error
CS1963: An expression tree may not contain a dynamic operation
You should not cast your IEnumerable
to the SelectList
- you need to create a new instance of it:
<%= Html.DropDownListFor(x => x.SelectedEmployee, new SelectList(Model.Employees)) %>
Update. While the comment above holds, the actual problem turned out to be dynamically typed view. Such views do not allow use of lambdas in helpers, such as x => x.SelectedEmployee
in question. So the actual solution to the problem was making view strogly typed:
Inherits="System.Web.Mvc.ViewPage<Namespace.EmployeeDetailsModel>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments