I have a table which shows every enrollment a student has to a course. I have a foreach loop looping through all the enrollments for the student
@foreach (var item in Model.Enrollments)
{
<tr>
<td> @Html.DisplayFor(modelItem => item.Course.CourseID) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Title) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Type) </td>
<td> @Html.DisplayFor(modelItem => item.Status) </td>
</tr>
}
Now this works all fine as expected, but when I try to show only courses that have a certain type using an if statement
@foreach (var item in Model.Enrollments)
{
if (item.Course.Type == "Basic Core")
{
<tr>
<td> @Html.DisplayFor(modelItem => item.Course.CourseID) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Title) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Type) </td>
<td> @Html.DisplayFor(modelItem => item.Status) </td>
</tr>
}
}
I get
"Object reference not set to an instance of an object." error on line 115
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 113:{
Line 114:
Line 115: if (item.Course.Type == "Basic Core") {
Line 116: <tr>
Line 117: <td> @Html.DisplayFor(modelItem => item.Course.CourseID) </td>
In my understanding a foreach loop would skip any null objects if there are any. Any help would be greatly appreciated.
Here is my controller
public ActionResult Details(int? StudentID)
{
if (StudentID == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(StudentID);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}