MVC下拉列表 - null错误

时间:2014-11-19 15:36:31

标签: model-view-controller

我使用Entity Framework生成了Models类。 这就是我得到的:

public partial class Employees
{
    public Employees()
    {
        this.Employees1 = new HashSet<Employees>();
        this.Vacations = new HashSet<Vacations>();
    }

    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string Phone { get; set; }
    public string JobTitle { get; set; }
    public int ManagerID { get; set; }
    public string LastUpdatedBy { get; set; }
    public Nullable<System.DateTime> LastUpdatedDate { get; set; }
    public bool Status { get; set; }

    public virtual ICollection<Employees> Employees1 { get; set; }
    public virtual Employees Manager { get; set; }
    public virtual ICollection<Vacations> Vacations { get; set; }
}

然后我为该类创建了View Model:

public class EmployeeViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string Phone { get; set; }
    public string JobTitle { get; set; }
    public int ManagerID { get; set; }
    public string ManagerFullName
    {
        get
        {
            return FirstName + " " + LastName;
        }

    }
    public bool Status { get; set; }

    public virtual ICollection<Employees> Employees1 { get; set; }
    public virtual Employees Manager { get; set; }


}

在EmplyeeControler课程中,我有动作:

public ActionResult Create()
{
    EmployeeViewModel employeeVM = new EmployeeViewModel();
    ViewBag.Employees1 = new SelectList(employeeVM.Employees1, "EmployeeID", "ManagerFullName");
    return View(employeeVM);
}

并查看:

<div class="editor-label">
    @Html.LabelFor(model => model.ManagerID, "Manager")
</div>
<div class="editor-field">
    @Html.DropDownList("ManagerID", "--- Select Manager ---")
    @Html.ValidationMessageFor(model => model.ManagerFullName)
</div>

但是我收到了错误:

  

值不能为空。参数名称:items

 ViewBag.Employees1 = new SelectList(employeeVM.Employees1, "EmployeeID", "ManagerFullName");

我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

<div class="editor-label">
    @Html.LabelFor(model => model.ManagerID, "Manager")
</div>
<div class="editor-field">
  @Html.DropDownListFor(x => x.ManagerID, (IEnumerable<SelectListItem>)ViewBag.Employees1,"--- Select Manager ---"));
    @Html.ValidationMessageFor(model => model.ManagerFullName)
</div>

更多详情请参阅此link