View 在ASP.NET MVC中将多个模型传递给视图

View 在ASP.NET MVC中将多个模型传递给视图,view,model,View,Model,我需要在同一个视图中传递两个模型,但是有些元素具有相同的名称 我有两个模型Employee和HolidayRequestForm,我需要在一个视图中使用这两个模型,该视图将成为每个员工的详细信息页面 这是我的员工: public partial class Employee { public int EmployeeID { get; set; } public string FullName { get; set; } public string EmailID {

我需要在同一个视图中传递两个模型,但是有些元素具有相同的名称

我有两个模型
Employee
HolidayRequestForm
,我需要在一个视图中使用这两个模型,该视图将成为每个员工的详细信息页面

这是我的
员工

public partial class Employee
{ 
    public int EmployeeID { get; set; }
    public string FullName { get; set; }
    public string EmailID { get; set; }
    public string Password { get; set; }
    public System.DateTime StartDate { get; set; }
    public int RoleID { get; set; }
    public int ShiftID { get; set; }
    public int AreaID { get; set; }
    public int DisciplineID { get; set; }
    public int SiteID { get; set; }
    public int ALCategory { get; set; }
    public Nullable<int> HoursTaken { get; set; }
    public Nullable<int> AwardedLeave { get; set; }
    public Nullable<int> TotalHoursThisYear { get; set; }
    public int HoursCarriedForward { get; set; }
    public Nullable<int> EntitlementRemainingThisYear { get; set; }
    public string Comments { get; set; }

   }
我曾尝试创建一个单独的模型,其中包含视图中要使用的所有元素,但我不确定如何区分具有相同名称的元素,例如注释,甚至可以这样做吗


我想在我的视图中使用这两种模型,因为我想创建一个员工个人资料页面,在页面顶部显示他们的个人资料信息,然后在页面底部的表格中使用holidayrequestform显示他们申请的假期

编写一个
ViewModel
,其中包含
Employee
HolidayRequestForm
,如下所示,然后将
ViewModel
传递给视图:

public class EmployeeViewModel
{
    public Employee Employee {get; set;}

    public HolidayRequestForm HolidayRequestForm {get; set;}
}
然后在你的行动方法中:

public ActionResult EmployeeDetails(int id)
{
     Employee employee =  _dbContext.Employees.FirstOrDefault(emp => emp.EmployeeID == id);
     HolidayRequestForm holidayRequestForm =  _dbContext.HolidayRequestForms.FirstOrDefault(hrf => hrf.EmployeeID == id);

     EmployeeViewModel employeeViewModel = new EmployeeViewModel()
     {
        Employee = employee,
        HolidayRequestForm  = holidayRequestForm
     }

     return View(employeeViewModel);
}
然后在视图中,访问模型属性,如下所示:

@model EmployeeViewModel

<p>Full Name: @Model.Employee.FullName</p>
@model EmployeeViewModel
全名:@Model.Employee.FullName


如何将模型绑定到视图?项目名称是否类似于
@model LotusWorksHT.Models.EmployeeViewModel
LotusWorksHT。是的!它应该是完全限定的名称空间!如果您的
EmployeeViewModel
位于
LotusWorksHT
项目的
Models
文件夹中,那么它应该是
@model LotusWorksHT.Models.EmployeeViewModel
,正如您所说。嗯,当我使用
全名:@model.Employee.FullName
时,我得到一个空异常。但后来我尝试了
@Html.DisplayNameFor(model=>model.Employee.FullName)
,但没有显示任何数据。我怀疑数据没有被传递到视图中??还是把模型搞砸了?谢谢你的帮助,我总算开始了。@Conor8630这意味着你在
EmployeeViewModel
中的
Employee
为空!在方法中进行调试,以确保它正在从数据库中提取
Employee
数据。
@model EmployeeViewModel

<p>Full Name: @Model.Employee.FullName</p>