我对ASP.NET MVC还是很陌生。我正在创建一个假期跟踪应用程序,并试图为每个员工创建一个详细信息页面。我希望该页面显示一个表,该表显示员工已采取的所有假期请求的表。我已经使它工作了,但只显示了一行。
这是我的模特
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;}
}
员工模型:
public class EmployeeViewModel
{
public Employee Employee { get; set; }
public HolidayRequestForm HolidayRequestForm { get; set; }
}
假日申请表模型:
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; }
public virtual Employee Employee { get; set; }
}
控制器操作:
public ActionResult Details(int? id)
{
Employee employee = db.Employees.FirstOrDefault(emp => emp.EmployeeID == id);
HolidayRequestForm holidayRequestForm db.HolidayRequestForms.FirstOrDefault(emp => emp.EmployeeID == id);
EmployeeViewModel employeeViewModel = new EmployeeViewModel()
{
Employee = employee,
HolidayRequestForm = holidayRequestForm,
};
return View(employeeViewModel);
}
My View只是一个HTML表,用于显示数据库中的数据。 所以问题是如何显示多个行或条目?我使用的是FirstorDefault吗?
答案 0 :(得分:3)
您必须更改Employee Model并为Holiday声明一个列表:
员工模型:
public class EmployeeViewModel
{
public Employee Employee { get; set; }
public List<HolidayRequestForm> HolidayRequestForm { get; set; }
}
控制器操作:
public ActionResult Details(int? id)
{
Employee employee = db.Employees.FirstOrDefault(emp => emp.EmployeeID == id);
List<HolidayRequestForm> holidayRequestForm = db.HolidayRequestForms.Where(emp => emp.EmployeeID == id).ToList();
EmployeeViewModel employeeViewModel = new EmployeeViewModel()
{
Employee = employee,
HolidayRequestForm = holidayRequestForm,
};
return View(employeeViewModel);
}