2015-11-07 33 views
2

我有一個基本的MVC視圖,將列出我所有的屬性。屬性模型編碼是這樣的:剃刀當試圖顯示項目時得到空引用項目

public class Property 
{ 

    public int Id { get; set; } 

    [Display(Name = "Type")] 
    public PropertyType Type { get; set; } 

    [Display(Name = "Address")] 
    public Address Address { get; set; } 

    [Display(Name = "Area")] 
    [Required(ErrorMessage = "A property area is required.")] 
    public double Area { get; set; } 

} 

基本上我有2個外鍵:類型和地址。我已經能夠插入一些信息到數據庫中,如下圖所示:

enter image description here

因此數據庫中包含的信息,但每次我打電話索引視圖列出所有的屬性,我得到一個NullReferenceException。

@foreach (var item in Model) { 
<tr> 
    <td> 
     @Html.Display(item.Type.Id.ToString()) 
    </td> 
    <td> 
     @Html.Display(item.Address.Id.ToString()) 
    </td> 
    <td> 
     @Html.DisplayFor(modelItem => item.Area) 
    </td> 
    <td> 
     @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | 
     @Html.ActionLink("Details", "Details", new { id=item.Id }) | 
     @Html.ActionLink("Delete", "Delete", new { id=item.Id }) 
    </td> 
</tr> 

編輯:空值從控制器正在添加類,就像這樣:

public ActionResult Index() 
    { 
     return View(db.Properties.ToList()); 
    } 

enter image description here

我能做些什麼?

回答

4

如果您正在使用EF則需要使用包含您的導航屬性:

db.Properties.Include(i => i.Address).Include(i => i.Type).ToList() 

這將使內部連接和你的屬性應該被填充。

欲瞭解更多信息,請閱讀docs

+0

你先生是男人。非常感謝你! –

1
@Html.DisplayFor(modelItem => item.Area) 

我想這是拋出錯誤的線。

拿出來看看是否仍然發生錯誤。