2015-02-09 38 views
0

我有一張表格,顯示了學生對課程的每個註冊。我有一個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); 
} 
+4

你內心的'Course'對象爲null,這就是錯誤的原因。如果條件 – 2015-02-09 07:43:48

回答

0

由於代碼的編碼器指出,你必須包含設置爲null課程對象的項目對象。

由於item對象不爲null,因此它從枚舉中拾取。然後,在檢查內部Course對象時,它拋出異常,因爲它是空的。爲了避免評估對象,像這樣前剛剛檢查空:

@foreach (var item in Model.Enrollments) 
{ 
if (item.Course != null && 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> 
    }        
} 

你也可以調試剃刀代碼,看看是否需要發生了什麼。

+0

之前檢查爲空謝謝你,您的評論解決了問題,並完美地說明了解決方案。 – 2015-02-10 08:14:44

+0

謝謝,很高興它幫助你Niko。 – SBirthare 2015-02-10 08:43:53

相關問題