Reputation: 1214
I have a basic view in MVC that will list all my properties. The properties model is coded this way:
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; }
}
Basically I've two foreign keys: Type and Address. I was already able to insert some information into the database as shown below:
So the database contains the information but everytime I call the Index view to list all the Properties I get a 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>
EDIT: The null values are comming from the Controller class just like so:
public ActionResult Index()
{
return View(db.Properties.ToList());
}
What can I do?
Upvotes: 2
Views: 925
Reputation: 1808
@Html.DisplayFor(modelItem => item.Area)
I imagine this is the line thats throwing the error.
Take it out see if the error still occurs.
Upvotes: 1
Reputation: 1816
If you are using EF you need to include your navigation properties using:
db.Properties.Include(i => i.Address).Include(i => i.Type).ToList()
This will make inner joins and your properties should be populated.
For more information read some docs.
Upvotes: 4