Controller
public ActionResult Index(int? StaffID, int? id)
{
//var userEmail = User.Identity.Name;
//var model = db.Staffs.Where(i => i.Email == userEmail).Include(x => x.Histories).Include(x => x.CurrentApplications).FirstOrDefault();
//return View(model);
var model = new LeaveIndexData();
var userEmail = User.Identity.Name;
model.Staffs = db.Staffs
.Where(i => i.Email == userEmail);
if(id != null)
{
ViewBag.StaffId = id.Value;
model.CurrentApplications = model.Staffs
.Where(i => i.StaffID == id.Value).Single().CurrentApplication;
}
return View(model);
}
Index View
@model test.ViewModel.LeaveIndexData
@{
ViewBag.Title = "Index";
}
@*<table class="table">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Hire Date</th>
<th>Office</th>
<th>Courses</th>
<th></th>
</tr>
@foreach (var item in Model.Instructors)
{
string selectedRow = "";
if (item.ID == ViewBag.InstructorID)
{
selectedRow = "success";
}
<tr class="@selectedRow">
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstMidName)*@
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
@foreach (var item in Model.Staffs) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.AllocatedLeave)
</td>
<td>
@Html.DisplayFor(modelItem => item.BalanceLeave)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StaffID }) |
@Html.ActionLink("Details", "Details", new { id=item.StaffID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.StaffID })
</td>
</tr>
}
</table>
@if (Model.CurrentApplications != null)
{
<h2>Current Applications</h2>
<table class="table">
<tr>
<th>Start Date</th>
<th>End Date</th>
<th>Leave Type</th>
<th>Period</th>
<th>Application Status</th>
<th>Leave Reason</th>
</tr>
@foreach (var item in Model.CurrentApplications)
{
if(item.StaffID == ViewBag.StaffID)
{
<tr>
<td>@item.StartDate</td>
<td>@item.EndDate</td>
<td>@item.LeaveType</td>
<td>@item.NoOfDays</td>
<td>@item.AppStatus</td>
<td>@item.LeaveReason</td>
</tr>
}
}
</table>
}
Staff Class
namespace test.Models
{
using System;
using System.Collections.Generic;
public partial class Staff
{
public int StaffID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Nullable<decimal> AllocatedLeave { get; set; }
public Nullable<int> BalanceLeave { get; set; }
public virtual History History { get; set; }
public virtual ICollection<CurrentApplication> CurrentApplication { get; set; }
}
}
I cannot figure out why my Current Applications table isn't displaying. If I remove the line @if (Model.CurrentApplications != null), I get this error:
Object reference not set to an instance of an object
Not sure if it's useful, but I'm using EntityFramework and my tables were generated from my database?