This is part 2 of the article. It focuses on consuming the .NET Core API created in part 1, and binding the data in our Blazor app. By the end of the article, we will have a fully functional Blazor site with Add/Edit and Delete features.
Prerequisites
This article assumes you have a basic working knowledge of Blazor web assembly and .NET Core.
We will be consuming the .NET Core API created in the first part to bind in our Blazor client app.
Through this article, we will cover the following topics:
- Create and register data service in Blazor to consume a .NET Core API.
- Creating Blazor razor pages and data binding.
- Creating a custom Blazor component for Add Employee.
Output
Employee Home Page
Employee Detail Page
Implementation
Step 1 - Create and register data service in Blazor to consume .NET Core API
Create a new folder service in EmployeePortal.Client and add IEmployeeDataService.
This will contain a definition of all the methods to be used in EmployeeDataService.
IEmployeeDataService
- public interface IEmployeeDataService {
- Task < IEnumerable < Employee >> GetAllEmployees();
- Task < Employee > AddEmployee(Employee employee);
- Task < Employee > GetEmployeeDetails(int employeeId);
- Task UpdateEmployee(Employee employee);
- Task DeleteEmployee(int employeeId);
- }
EmployeeDataService
- public class EmployeeDataService: IEmployeeDataService {
- private readonly HttpClient _httpClient;
- public EmployeeDataService(HttpClient httpClient) {
- _httpClient = httpClient;
- }
- public async Task < IEnumerable < Employee >> GetAllEmployees() {
- return await JsonSerializer.DeserializeAsync < IEnumerable < Employee >> (await _httpClient.GetStreamAsync($ "api/employee"), new JsonSerializerOptions() {
- PropertyNameCaseInsensitive = true
- });
- }
- public async Task < Employee > AddEmployee(Employee employee) {
- var employeeJson = new StringContent(JsonSerializer.Serialize(employee), Encoding.UTF8, "application/json");
- var response = await _httpClient.PostAsync($ "api/employee", employeeJson);
- if (response.IsSuccessStatusCode) {
- return await JsonSerializer.DeserializeAsync < Employee > (await response.Content.ReadAsStreamAsync());
- }
- return null;
- }
- public async Task < Employee > GetEmployeeDetails(int employeeId) {
- return await JsonSerializer.DeserializeAsync < Employee > (await _httpClient.GetStreamAsync($ "api/employee/{employeeId}"), new JsonSerializerOptions() {
- PropertyNameCaseInsensitive = true
- });
- }
- public async Task UpdateEmployee(Employee employee) {
- var employeeJson = new StringContent(JsonSerializer.Serialize(employee), Encoding.UTF8, "application/json");
- await _httpClient.PutAsync("api/employee", employeeJson);
- }
- public async Task DeleteEmployee(int employeeId) {
- await _httpClient.DeleteAsync($ "api/employee/{employeeId}");
- }
- }
Register EmployeeDataService and IEmployeeDataService in program.cs of cllient app
builder.Services.AddHttpClient<IEmployeeDataService, EmployeeDataService>(client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));
Step 2 - Creating Blazor razor pages and data binding
Add a new Razor component and EmployeePage class inside the pages folder.
EmployeePage.cs
- public partial class EmployeePage: ComponentBase {
- public IEnumerable < EmployeePortal.Shared.Employee > Employees {
- get;
- set;
- }
- [Inject]
- public IEmployeeDataService EmployeeDataService {
- get;
- set;
- }
- public AddEmployeeDialog AddEmployeeDialog {
- get;
- set;
- }
- protected async override Task OnInitializedAsync() {
- Employees = (await EmployeeDataService.GetAllEmployees()).ToList();
- }
- protected void QuickAddEmployee() {
- AddEmployeeDialog.Show();
- }
- public async void AddEmployeeDialog_OnDialogClose() {
- Employees = (await EmployeeDataService.GetAllEmployees()).ToList();
- StateHasChanged();
- }
- }
Employee page class will inherit from the Component base.
OnInitializedAsync will be called when the componenet is been Initialized and we would call GetAllEmployees at this point in time.
IEmployeeDataService needs to be injected to call the GetAllEmployees method.
Employeerazor
- @page "/"
- @using EmployeePortal.Client.Components;
- <h1 class="page-title">All employees</h1>
- @if (Employees == null)
- {
- <p>
- <em>Loading...</em>
- </p>
- }
- else
- {
- <table class="table">
- <thead>
- <tr>
- <th>Employee ID</th>
- <th>First name</th>
- <th>Last name</th>
- <th></th>
- </tr>
- </thead>
- <tbody>
- @foreach (var employee in Employees)
- {
- <tr>
- <td>@employee.EmployeeId</td>
- <td>@employee.FirstName</td>
- <td>@employee.LastName</td>
- <td>
- <a href="@($"detail/{employee.EmployeeId}")" class="btn btn-primary-details table-btn">
- <i class="fas fa-info-circle"></i>
- Details
-
- </a>
- <a Edit href="@($"edit/{employee.EmployeeId}")" class="btn btn-primary-edit table-btn">
- <i class="fas fa-edit"></i>
- Edit
-
- </a>
- </td>
- </tr>
- }
- </tbody>
- </table>
- }
- <button @onclick="QuickAddEmployee" class="btn btn-dark table-btn quick-add-btn"> + </button>
- <AddEmployeeDialog @ref="AddEmployeeDialog" CloseEventCallback="@AddEmployeeDialog_OnDialogClose"></AddEmployeeDialog>
Run the application on your local machine.
You will able to see a list of employees and also able to Edit and Delete using our UI.
Step 3 - Creating a custom Blazor component to Add Employee.
We will be using a Modal pop up to allow users to add a new Employee.
This Modal pop up will be a custom Blazor component. It will have also basic validations for user input.
I had posted a dedicated
article for creating and using Custom Add Employee Modal in our project.
Once the AddEmployee Component is integrated on EmployeePage we would able to add new Employee and the Employee list is refreshed with new data.
Summary
In this article, we learned how to create a fully functional Blazor web assembly app. In our next article, we will deploy this app to Azure using the PAAS model and Azure SQL to store user data.
Thanks a lot for reading. I hope you liked this article. Please share your valuable suggestions and feedback. Write in the comment box in case you have any questions. Have a good day!