2017-02-06 62 views
-1

我偶然發現了一個錯誤,當我嘗試訪問我的ICollection內容時。 代碼如下: 查看無法訪問ICollection數據在視圖中

foreach (var carInfo in Model) 
{ 
    @carInfo.Id 
    @carInfo.Brand 
    ......... ect. 

    foreach (var rentInfo in carInfo.RentInfo) 
    { 
     @rentInfo.RentDate 
     ....... ect. 
    } 
} 

查看頂部:

@model IEnumerable<TestApp.Models.Cars> 

汽車模型:

public class Cars 
{ 
    public int Id { get; set; } 
    public string CarPlateNumber { get; set; } 
    public string Brand { get; set; } 
    public string Fullname { get; set; } 
    public string Category { get; set; } 
    public int ReleaseDate { get; set; } 
    public int SeatCount { get; set; } 
    public string GearBox { get; set; } 

    public virtual ICollection<CarRent> RentInfo { get; set; } 
} 

如果我刪除代碼:

foreach (var rentInfo in carInfo.RentInfo) 
     { 
      @rentInfo.RentDate 
      ....... ect. 
     } 

一切WOR ks很好,問題是爲什麼這個aprouch不起作用?

+0

你有什麼錯誤? –

+0

什麼是錯誤?嘗試'@foreach ...'並在訪問變量時刪除@。 – Developer

+0

無法加載資源:服務器響應的狀態爲500(內部服務器錯誤) –

回答

0

我確實發現了我的錯誤。這個問題很簡單,只要我的ICollection從db返回null就會發生這個錯誤。所以我確實把簡單的if語句來檢查wheather參考:

carInfo.RentInfo 

是不是null,只有然後執行foreach命令。謝謝大家幫助。