I have an Invoice Class with FoodId and UserId foreign keys to FoodItem and User table.
I have the following razor page Index.cshtml from adding a scaffolded item to the controllers folder.
@model IEnumerable<WebApplication1.Models.Invoice>
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link rel="stylesheet" href="~/css/SideBar.css" />
<div class="sidebar">
<a asp-controller="Admin">Main Page</a>
<a asp-controller="FoodItems">Food List</a>
<a class="active" asp-controller="Invoices">Invoice</a>
<a asp-controller="Role">Users & Roles</a></div>
<h1>Invoice</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.UserId)
</th>
<th>
@Html.DisplayNameFor(model => model.FoodId)
</th>
<th>
@Html.DisplayNameFor(model => model.totalsum)
</th>
<th>
@Html.DisplayNameFor(model => model.quantity)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
@Html.DisplayFor(modelItem => item.FoodId)
</td>
<td>
@Html.DisplayFor(modelItem => item.totalsum)
</td>
<td>
@Html.DisplayFor(modelItem => item.quantity)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.InvoiceId">Edit</a> |
<a asp-action="Details" asp-route-id="@item.InvoiceId">Details</a> |
<a asp-action="Delete" asp-route-id="@item.InvoiceId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
I want to list instead of the FoodId and UserId , bring the columns foodname and username from the FoodItem and UserId tables. How can I achieve that?
When you retrieve Invoice entity include food and user like this:
_context.Invoices.Include(x => x.Users).Include(x => x.Food).ToList();
And then in your view write like this ;
@Html.DisplayNameFor(model => model.User.Name)
@Html.DisplayNameFor(model => model.Food.Name)