我需要在同一视图中传递两个模型,但是某些元素具有相同的名称。
我有两个模型Employee
和HolidayRequestForm
,我需要在一个视图中使用这两个模型,这将是每个员工的详细信息页面。
这是我的Employee
:
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
:
public partial class HolidayRequestForm
{
public int RequestID { get; set; }
public int EmployeeID { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime FinishDate { get; set; }
public int HoursTaken { get; set; }
public string Comments { get; set; }
public int YearCreated { get; set; }
public int MonthCreated { get; set; }
public Nullable<int> DayCreated { get; set; }
public Nullable<int> YearOfHoliday { get; set; }
}
我尝试创建一个单独的模型,其中包含要在视图中使用的所有元素,但是我不确定如何区分具有相同名称的元素,例如。评论甚至有可能这样做吗?
我想在我的视图中同时使用这两种模型,因为我想创建一个“雇员资料”页面,其信息在顶部显示有关其资料的信息,然后显示他们在表格中使用holidayrequestform请求的假期。页面底部。
答案 0 :(得分:2)
编写一个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>