DropDownFor issue in MVC 3

I'm new to the Entity Framework and ran into a little problem with the 'DropDownListFor 'method in the UI. I would like to stay consistent with in building loosely-coupled components as much as possible. Here is the scenerio, each employee can only be associated with one department, and a department can be associated with many employees. When I add an employee to the database, I would like to select the department from a drop-down list, which is populated from the departments table. This is straight-forward, however, when I create a new employee, it gives me this error (pictured below). When using the ViewResult edit method, the drop-down list works fine.

I was thinking, could this be a result that a department id doesn't yet exist for the employee? Then on the other hand, these values are from the departments table, so it shouldn't matter if a department id exists yet or not. Any help would be appreciated.
[Table("Employees")]
    // The employee class
    public class EEmployee
    {
        [Key]
        public int EmployeeID { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsDateAdded { get; set; }
        public DateTime DateAdded { get; set; }
        public DateTime DateModified { get; set; }
        public string AddedBy { get; set; }
        public string ModifiedBy { get; set; }
        public string Notes { get; set; }

        #region Foreign keys and navagation properties
        // An employee can only have one department.
        public int DepartmentID { get; set; }
        public EDepartment Department { get; set; }

        // An employee can have many EmployeeLdrs.
        public ICollection<ELdrEmployeeProductionRecord> Ldrs_Employees_ProductionRecords { get; set; }

        // An employee can have many error reports.
        public ICollection<EErrorReport> ErrorReports { get; set; }

        // An employee can have many transfer ins.
        public ICollection<ETransferIn> TransferIns { get; set; }

        // An employee can have many transfer outs.
        public ICollection<ETransferOut> TransferOuts { get; set; }
        #endregion
    }

Open in new window

// The IEmployeeRepository interface
public interface IEmployeeRepository
    {
        IQueryable<EEmployee> Employees { get; }
        void Save(EEmployee employee);
        void Delete(EEmployee employee);
        IEnumerable<EDepartment> Departments { get; }
    }

Open in new window

// The employee concrete type for EF
public class EFEmployeeRepository : IEmployeeRepository
    {
        private EFBrodartProjectContext context = new EFBrodartProjectContext();

        public IQueryable<EEmployee> Employees
        {
            get { return context.Employees; }
        }

        public IEnumerable<EDepartment> Departments
        {
            get { return context.Departments; }
        }

        public void Save(EEmployee employee)
        {
            if (employee.EmployeeID == 0)
            {
                context.Employees.Add(employee);
                context.SaveChanges();
            }

            context.SaveChanges();
        }

        public void Delete(EEmployee employee)
        {
            context.Employees.Remove(employee);
            context.SaveChanges();
        }
    }

Open in new window

// Custom employee view model
public class VMEmployee
    {
        public EEmployee Employee { get; set; }
        public IEnumerable<EEmployee> Employees { get; set; }
        public EDepartment Department { get; set; }
        public IEnumerable<EDepartment> Departments { get; set; }
        public VMPaging Paging { get; set; }
    }

Open in new window

private readonly IEmployeeRepository employeeRepository;

        public EmployeeController(IEmployeeRepository employeeRepository)
        {
            if (employeeRepository == null)
            {
                throw new ArgumentNullException("An error has occurred. Please try again.");

                // Dump error messages into the database.
            }
            else
            {
                this.employeeRepository = employeeRepository;
            }
        }

public ViewResult Edit(int id)
        {
            VMEmployee viewModel = new VMEmployee
            {
                Employee = employeeRepository.Employees.FirstOrDefault(e => e.EmployeeID == id),
                Departments = employeeRepository.Departments.ToList()
            };
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Edit(EEmployee employee)
        {
            if (ModelState.IsValid)
            {
                employeeRepository.Save(employee);
                TempData["SaveMessage"] = string.Format("{0} {1} has been saved successfully.",
                    employee.FirstName, employee.LastName);
                return RedirectToAction("List");
            }
            else
            {
                TempData["SaveMessage"] = string.Format("An error has occurred. {0} {1} was not saved.",
                    employee.FirstName, employee.LastName);
                return View(employee);
            }
        }

        public ViewResult Create()
        {
            return View("Edit", new VMEmployee { Employee = new EEmployee() });
        }

Open in new window

<tr>
                <td class="display-label">Department:</td>
                <td class="display-field">@Html.DropDownListFor(m => m.Employee.DepartmentID,
                    new SelectList(Model.Departments, "DepartmentID", "Name"))</td>
            </tr>

Open in new window

error.jpg
Keith1985Asked:
Who is Participating?
 
Craig WagnerSoftware ArchitectCommented:
Your Create() method is returning a view model that doesn't have the Departments populated. When the view tries to create the DropDown the object is null.

            VMEmployee viewModel = new VMEmployee
            {
                Employee = new EEmployee(),
                Departments = employeeRepository.Departments.ToList()
            };
            return View(viewModel);
0
 
Keith1985Author Commented:
Right on. Thank you very much.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.