简体   繁体   中英

MVC Populating Dropdown from Database

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>

Because Employees is an IEnumerable<SelectListItem> , you don't need to cast it or create a new SelectList() , you can just use it directly.

Also I suspect you are missing a .ToList()

public ActionResult MiEmployeeDetails()
{
  var model = new EmployeeDetailsModel();
  model.Employees = _db.geo_employees.ToList().Select(x => new SelectListItem
   {
      Value = x.name,
      Text = x.name
   }).ToList();

   return View(model);
}

ToList should be moved to the end of the statement:

model.Employees = _db.geo_employees.Select(x => new SelectListItem
{
   Value = x.name,
   Text = x.name
}).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM