我有一張表格,顯示了學生對課程的每個註冊。我有一個foreach循環遍歷所有入學的學生循環當試圖在foreach循環中使用if語句時,「對象引用未設置爲對象的實例」
@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>
}
現在這個工程預期都很好,但是當我嘗試僅顯示有某種類型的課程中使用if語句
@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>
}
}
我得到
"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>
在我的理解foreach循環將跳過如果任何空對象有任何。任何幫助將不勝感激。
這裏是我的控制器
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);
}
你內心的'Course'對象爲null,這就是錯誤的原因。如果條件 – 2015-02-09 07:43:48