简体   繁体   English

MVC从数据库填充下拉列表

[英]MVC Populating Dropdown from Database

New to MVC trying to populate a dropdown from Database, proving a bit more tricky than I imagined. MVC的新成员试图填充数据库中的下拉菜单,事实证明,这个过程比我想象的要复杂得多。

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 CS1963:表达式树可能不包含动态操作

You should not cast your IEnumerable to the SelectList - you need to create a new instance of it: 您不应该将IEnumerable转换为SelectList您需要为其创建一个新实例:

<%= 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. 这样的视图不允许在助手中使用lambda,例如x => x.SelectedEmployee 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. 由于EmployeesIEnumerable<SelectListItem> ,因此您无需IEnumerable<SelectListItem>转换或创建new SelectList() ,就可以直接使用它。

Also I suspect you are missing a .ToList() 我也怀疑你缺少一个.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: ToList应该移到语句的末尾:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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