Nate Hitze
Nate Hitze

Reputation: 988

MVC 5 Model properties null but database contains value

My models:

public class Inventory
{
    public int ID { get; set; }
    public float Amount { get; set; }
    public ApplicationUser Owner { get; set; }
    public Item Item { get; set; }
    public Unit Unit { get; set; }
}
public class Unit
{
    public int ID { get; set; }
    public string Abbreviation { get; set; }
    public string FullName { get; set; }
    public UnitType Type { get; set; }
}

When passing all of my Inventorys in the controller to the view, the Unit field is always null in the view, regardless of what is in the database.

Action in controller that is being called:

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

Relevant view parts:

@model IEnumerable<App.Models.Inventory>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Amount)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Unit.Abbreviation)
        </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>
}

The second DisplayFor (item.Unit.Abbreviation) never shows anything. I put a breakpoint on the view and none of the models in Model have a value for the references to other models.

Database data (links to images because I don't have enough Rep):

Inventory

Units

I am using code first development.

Upvotes: 0

Views: 449

Answers (1)

faby
faby

Reputation: 7558

I think that the problem is that you aren't retrieving Unit records. if the schema of your database has foreign keys set correctly you can try this

public ActionResult Index()
{
    return View(db.Inventorys.Include(b => b.Unit_ID).ToList() );
}

refer this

Upvotes: 1

Related Questions