I'm joining multiple tables using linq. The problem is, I have to join a table, that will have some null values in some rows. I think the join itself is working fine, but when I iterate through my ViewBag, I get an error because of the null values.
This is my code: Controller:
ViewBag.coaching = (from kst in db.kursister
join kursus_kursist in db.kursus_kursist
on kst.kursist_id equals kursus_kursist.kursist_id
join kursus in db.kurser
on kursus_kursist.kursus_id equals kursus.kursus_id
join coach in db.jobcoach
on kst.kursist_id equals coach.kursist_id into coachJoin
where kursus.kursus_id == id
from cj in coachJoin.DefaultIfEmpty()
select new CoachHoldModel { kst = kst, kursus = kursus, cj = cj });
Here's my view:
@model IEnumerable<Itucation.Models.CoachHoldModel>
@{
ViewBag.Title = "Karriere Coach Hold";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Protokol</h2>
<div>
<h3>
@{
foreach (var navn in (ViewBag.kursus))
{
@navn.kursus_navn
}
}
</h3>
<table class="table-bordered">
<tr>
<td colspan="2" style="border:0;"></td>
<th>Status</th>
<td><img src="~/Content/Images/logo.png" height="30" /></td>
</tr>
@{
foreach (var item in (ViewBag.coaching))
{
<tr>
<td>@item.kst.fornavn</td>
<td>@item.kst.efternavn</td>
<td>
@item.cj.status
</td>
<td colspan="2"></td>
</tr>
}
}
</table>
</div>
It is the @item.cj.status that will contain null values.
The forech loop iterates through a list of students. Some students have a status set, some do not. i would like to display the value for the students, who have a status value - and ignore the others.
Any help would be greatly appreciated.
Why not test if it's not null and then show the status?
<td>
@if (item.cj != null) // or item.cj?.status
{
<span>@item.cj.status</span>
}
</td>