Delete database row from blazor


In this video we will implement Delete operation in Blazor i.e delete employee row from the Employees database table through a blazor web application.

delete database row from blazor

EditEmployee.razor

EditEmployee component is used for both

    1. Editing existing employee data and
  1. Creating a new employee

Delete button must not be displayed when we are creating a new employee, hence we check if EditEmployeeModel.EmployeeId > 0

@if (EditEmployeeModel.EmployeeId > 0)
{
    <button class="btn btn-danger" type="button" @onclick="Delete_Click">
        Delete
    </button>
}

EditEmployeeBase.cs

  • After the Employee row is deleted, redirect to EmployeeList component.
  • The URL path for EmployeeList component is "/"
protected async Task Delete_Click()
{
    await EmployeeService.DeleteEmployee(Employee.EmployeeId);
    NavigationManager.NavigateTo("/");
}

IEmployeeService.cs

public interface IEmployeeService
{
    Task DeleteEmployee(int id);
}

EmployeeService.cs

public class EmployeeService : IEmployeeService
{
    private readonly HttpClient httpClient;

    public EmployeeService(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

    public async Task DeleteEmployee(int id)
    {
        await httpClient.DeleteAsync($"api/employees/{id}");
    }
}

EmployeesController.cs

[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
    private readonly IEmployeeRepository employeeRepository;

    public EmployeesController(IEmployeeRepository employeeRepository)
    {
        this.employeeRepository = employeeRepository;
    }

    [HttpDelete("{id:int}")]
    public async Task<ActionResult<Employee>> DeleteEmployee(int id)
    {
        try
        {
            var employeeToDelete = await employeeRepository.GetEmployee(id);

            if (employeeToDelete == null)
            {
                return NotFound($"Employee with Id = {id} not found");
            }

            return await employeeRepository.DeleteEmployee(id);
        }
        catch (Exception)
        {
            return StatusCode(StatusCodes.Status500InternalServerError,
                "Error deleting data");
        }
    }
}




© 2020 Pragimtech. All Rights Reserved.