Link to home
Start Free TrialLog in
Avatar of Keith1985
Keith1985Flag for United States of America

asked on

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
ASKER CERTIFIED SOLUTION
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Keith1985

ASKER

Right on. Thank you very much.