Blazor: How to bind employees to table / grid
If you are new to Blazor, check the previous article how to create your first Blazor project with .NET 5.
What you will learn:
- How to create new Razor Component (new page)
- How to add a new navigation link for employees
- How to bind employees data to table/grid.
Step 1: Create a Models folder and create Employee.cs class
using System;
namespace BlazorAppDemo1.Models
{
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string Mobile { get; set; }
public string Country { get; set; }
}
}
Step 2: Add new Razor Component to Pages folder
Step 3: Name the Razor Component as Employee.razor.
Step 4: Add page url "/employees", inherit the employee razor component from ComponentBase as below.
@page "/employees"
@inherits ComponentBase
Step 5: Open NavMenu.razor page which is under the Shared folder.
Step 6: Add a new nav link for employees as below.
<li class="nav-item px-3">
<NavLink class="nav-link" href="/employees">
<span class="oi oi-list-rich" aria-hidden="true"></span> Employees
</NavLink>
</li>
Step 7: Declare employees
variable to hold the employee's collection.
@page "/employees"
@inherits ComponentBase
@using Models;
....
@code {
private List<Employee> employees;
}
Step 8: OnInitialized()
bind employees data to bind to the table.
@page "/employees"
@inherits ComponentBase
@using Models;
....
@code {
private List<Employee> employees;
protected override void OnInitialized()
{
// TODO: do something
}
}
@code {
private List<Employee> employees;
protected override void OnInitialized()
{
employees = new List<Employee>
{
new Employee{
EmployeeId = 101,
FirstName="Badri Ayaan",
LastName="Reddy",
DateOfBirth = DateTime.Now.AddYears(-20),
Mobile = "9988776655",
Country = "India"
},
new Employee{
EmployeeId = 102,
FirstName="Nithya Vikram",
LastName="Reddy",
DateOfBirth = DateTime.Now.AddYears(-18),
Mobile = "8877665544",
Country = "India"
}
};
}
}
Step 9: Loop through the employees
collection and render the table rows.
<h3>Employees</h3>
@if (employees == null)
{
<p>Loading Employees...</p>
}
else
{
<table class="table table-sm">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Id</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">DOB</th>
<th scope="col">Mobile</th>
<th scope="col">Country</th>
</tr>
</thead>
<tbody>
@{
var index = 1;
foreach (var item in employees)
{
<tr>
<th scope="row">@index</th>
<td>@item.EmployeeId</td>
<td>@item.FirstName</td>
<td>@item.LastName</td>
<td>@item.DateOfBirth</td>
<td>@item.Mobile</td>
<td>@item.Country</td>
</tr>
index++;
}
}
</tbody>
</table>
}
Step 10: Run the application and click on Employees link; you will see the below output:
We hope you like this article.
-
CreatedNov 29, 2020
-
UpdatedNov 29, 2020
-
Views1,766