Ricardo Mota
Ricardo Mota

Reputation: 1214

Razor get null reference when trying to display Item

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:

enter image description here

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());
    }

enter image description here

What can I do?

Upvotes: 2

Views: 925

Answers (2)

Darren Gourley
Darren Gourley

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

xZ6a33YaYEfmv
xZ6a33YaYEfmv

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

Related Questions