2017-05-04 69 views
0

对于我的网站应用程序项目,我有两个相互关联的模型。模型部门与模型员工相关。每个员工分配一个部门,而每个部门可以有多个员工。在部门视图中,我有一个“添加新员工”选项。当点击添加新员工按钮时,会弹出一个模式弹出窗口,其中显示雇员/创建视图。我的问题是我不知道如何将员工链接到部门,以便员工自动将其添加到右侧部门旁边的部门视图中。2种不同的模型 - 如何在MVC 5中连接它们?

现在,我的员工/创建视图只是给用户一个下拉列表的部门链接员工。我希望员工在“部门”视图中显示“添加员工”选项时自动链接到部门。

这里的系车型:

public class Department 
{ 
    [Key] 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string BuildingLocation { get; set; } 
    public string DirectLine { get; set; } 
    public virtual ICollection<Employee> Employees { get; set; } 

} 

这里的员工型号:

public class Employee 
    { 
     [Key] 
     public int EmployeeID { get; set; } 
     [ForeignKey("Department")] 
     public int DepartmentID { get; set; } 
     public string EmployeeFirstName { get; set; } 
     public string EmployeePosition { get; set; } 
     public string EmployeePhoneNo { get; set; } 
     public string EmployeeEmail { get; set; } 
     public virtual Department Department { get; set; } 
    } 

回答

1

我想你可以创建一个EmployeeViewModel。例如:

public class Employee 
    {   
     public int EmployeeID { get; set; }   
     public int DepartmentID { get; set; } 
     public string EmployeeFirstName { get; set; } 
     public string EmployeePosition { get; set; } 
     public string EmployeePhoneNo { get; set; } 
     public string EmployeeEmail { get; set; } 
     public SelectListItem DepartmentList { get; set; }   
    } 

当您单击按钮添加新员工时,只需设置您选择的DepartmentId = DepartmentId。或者您可以让用户更改Deparment。

+0

您可以改变它为部门视图模型吗?部门观点将成为主要观点。 –

+1

@VyNguyen:是的。你只需要一个模型,我的朋友:)) – Tomato32

+0

我应该用什么来存储部门视图模型中的员工?名单? ICollection的? –

0

您可以像这样创建一个ViewModel。无论何时想要在视图中显示员工详细信息,只需将数据与“DepartmentID”和“DepartmentName”一起映射到此视图模型。要获得“DepartmentName”,您可以加入部门表并获取部门名称。

public class EmployeeViewModel 
{ 
    public int EmployeeID { get; set; } 
    public string EmployeeFirstName { get; set; } 
    public string EmployeePosition { get; set; } 
    public string EmployeePhoneNo { get; set; } 
    public string EmployeeEmail { get; set; } 

    public int DepartmentID { get; set; } 
    public string DepartmentName { get; set; } 
    public virtual Department Department { get; set; } 
} 

要获取部门名称,您可以像这样加入Employe表。 (请注意,我在这里使用EntityFramework来检索数据)

var employeeList = from e in dbContext.Employees 
      join d in dbContext.Departments on e.DepartmentID equals d.DepartmentID 
      select new EmployeeViewModel 
      { 
       EmployeeID = e.EmployeeID, 
       EmployeeFirstName = e.EmployeeFirstName, 
       EmployeePosition = e.EmployeePosition, 
       EmployeePhoneNo = e.EmployeePhoneNo, 
       EmployeeEmail = e.EmployeeEmail, 
       EmployeePhoneNo = e.Name, 

       DepartmentID = e.DepartmentID, 
       DepartmentName = d.DepartmentName 
      };