I have a simple code where an Employee has a credit card
``` public class EmployeeModel : PageModel
{
private readonly EmployeeData EmployeeData;
private readonly CardData CardData;
public EmployeeModel(EmployeeData EmployeeData , CardData CardData)
{
this.EmployeeData = EmployeeData ;
this.CardData = CardData ;
}
[BindProperty(SupportsGet = true)]
public int EmployeeID { get; set; }
[BindProperty(SupportsGet = true)]
public int CardID { get; set; }
public Employee Employee { get; set; }
public Card Card { get; set; }
public void OnGet()
{
Employee = EmployeesData.GetEmployee(EmployeeID);
Card = CardData.GetCard(CardID);
}
}
@page
@model Web.Pages.EmployeeModel
@{
}
<table >
<tbody>
<tr >
<td>
<div >
<h6>ID employee</h6>
</div>
</td>
<td ><span>@Html.DisplayFor(model => model.Employee.EmployeeID)</span></td>
</tr>
</tbody>
</table>
<table >
<tbody>
<tr >
<td>
<div >
<h6>ID Card</h6>
</div>
</td>
<td ><span>@Html.DisplayFor(model => model.Card.CardID)</span></td>
</tr>
</tbody>
</table>
I try to display the values that I have in EmployeeModel to view page, but doesn't work. I try to do the next example, to put in my OnGet(int id) parameters and it work when I have a single employee, but when I try to do something more complex and add more employee the data doesn't display itself and the table its empty:
@page
@model Web.Pages.EmployeesModel
<div >
<div >
<div>
<h1 >EMPLOYEES</h1>
</div>
<table >
<thead>
<tr>
<th >ID</th>
</tr>
<thead>
<tbody>
@foreach (var employee in Model.employeeList)
{
<tr>
<td ><a asp-page="Employee" asp-route-id="@employee.EmployeeID">@employee.EmployeeID</a></td>
</tr>
}
</tbody>
</table>
</div>
</div>
Any Idea what's going on?
CodePudding user response:
You need to use the Employee
and Card
objects in razor as follows:
<td ><span>@Model.Employee.EmployeeID</span></td>
<td ><span>@Model.Card.CardID</span></td>
@Model
allows you to access the page model object directly. In your case this would be the EmployeeModel
instance.
You can refer to the below SO topic for the purposes of @Html.DisplayFor
:
What is the @Html.DisplayFor syntax for?
As for the last code section I am not sure where is @Model.employeeList
coming from. Doesn't this result to an error?
CodePudding user response:
I don't see the referenced employeeList
property in your Model that you defined. You may have it in your EmployeesModel
, but it's not in the code you posted. Ideally, you'd want a property something like below in your model.
public List<Employee> Employees { get; set; }
Then, in your OnGet()
method, populate that list from your data source.
Employees = EmployeesData.GetEmployees();
Then you can loop over that model property like you're trying to:
@foreach (var employee in Model.Employees)
{
...
}