Donate

Blazor Web App CRUD Project Using Visual Studio 2022, .NET 8 And Entity Framework Core

Good day Team!

Here's a basic Blazor Web App CRUD Project using Visual Studio 2022, .NET 8 and Entity Framework Core. The database for this project is SQL Server and the approach to communicate the database is database first. Let's begin.

I. Project Setup

1. Open your SSMS editor and execute the create Employee table script that is used in this project into your SQL Server instance. This will be the datasource for our employee information.
USE [ASPCoreTestDB]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employee](
	[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeGovtID] [varchar](50) NULL,
	[EmployeeName] [varchar](200) NULL,
	[Age] [int] NULL,
	[Address] [nvarchar](max) NULL,
	[Salary] [decimal](18, 2) NULL,
	[Designation] [varchar](50) NULL,
	[HasDependents] [bit] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
	[EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
2. Open Visual Studio 2022 and create a new Blazor Web App project. This is a new template for Blazor projects in .NET 8.
Blazor Web App CRUD Project Using Visual Studio 2022, .NET 8 And Entity Framework Core
3. Select .NET 8.0 as the target framework, check the Configure for HTTPS checkbox, choose Server for render mode and interactivity location is Per page/component.
Blazor Web App CRUD Project Using Visual Studio 2022, .NET 8 And Entity Framework Core
4. Create the following folders specifically Model, Data and Repository.
5. Add a new css file called Employee inside the wwwroot folder.
6. Within the Data folder, create new .cs file called EmployeeDBContext.
7. Inside the Model folder, create two .cs files namely Employee.cs and EmployeeRecord.cs
8. In the Repository folder, create an interface IRepository.cs and a Repository.cs class.
9. Remove the unnecessary components inside the Pages folder and retain the Home.razor and Error.razor components.
10. Add three new components in the Pages folder EmployeeAdd.razor, EmployeeDetails.razor and EmployeeUpdate.razor.
11. Add a new json file called libman.json. We will need to configure the fontawesome library here.
After The project structure should similar to the image below.
Blazor Web App CRUD Project Using Visual Studio 2022, .NET 8 And Entity Framework Core
12. Add the following Nuget packages: Microsoft.AspNetCore.Components.WebAssembly.Server, Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools.

II. External CSS, FontAwesome Library and appsettings.json

1. libman.json - Modify the json file by integrating the font-awesome icon library into this project. As of today, I'm using the 5.15.3 version.
{
  "version": "1.0",
  "defaultProvider": "cdnjs",
  "libraries": [
    {
      "library": "font-awesome@5.15.3",
      "destination": "wwwroot/lib/font-awesome/"
    }
  ]
}
2. Employee.css - Add the following styles to the css file.
#divCreateLink {
    margin-top: 40px;
    margin-bottom: 10px;
    color: white !important;
}

    #divCreateLink span {
        margin-left: 5px;
    }

.divCompanyHeader {
    margin-top: 50px;
    text-align: center;
}

#chkDependents {
    margin-left: 0px !important;
}

#spnDependents {
    margin-left: 20px;
}

table i {
    color: black;
}
3. appsettings.json - Add a connection string called EmployeeContext that points to your database server of which the Employee table is located. Replace the value of the connection string accordingly.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "EmployeeContext": "Server=.;Database=ASPCoreTestDB;Integrated Security=True;TrustServerCertificate=True;"
  },
  "AllowedHosts": "*"
}

III. Coding the Model, Data and Repository Files

1. Employee.cs - Add properties that will be mapped to the database columns using a context class.
public partial class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public string EmployeeGovtId { get; set; }
    public string EmployeeName { get; set; }
    public int? Age { get; set; }
    public string Address { get; set; }
    public decimal? Salary { get; set; }
    public string Designation { get; set; }
    public bool? HasDependents { get; set; }
}
2. EmployeeRecord.cs - Add properties that will be bound to the Blazor input controls. The property values of this class will then be assigned to an Employee object during save, update or viewing of details.
using System.ComponentModel.DataAnnotations;

namespace BlazorCrudApp.Model
{
    public class EmployeeRecord
    {
        public int EmployeeId { get; set; }

        [Display(Name = "Government ID")]
        [Required(ErrorMessage = "Government ID is required")]
        public string EmployeeGovtId { get; set; }

        [Display(Name = "Employee Name")]
        [Required(ErrorMessage = "Name is required")]
        public string EmployeeName { get; set; }

        [Required(ErrorMessage = "Age is required")]
        [Range(0, int.MaxValue, ErrorMessage = "Please enter integer number")]
        public int? Age { get; set; }

        [Required(ErrorMessage = "Address is required")]
        public string Address { get; set; }

        [Required]
        [Range(1000, 99999.99, ErrorMessage = "Please enter value from 1000 to 99999.99")]
        public decimal? Salary { get; set; }

        [Required(ErrorMessage = "Designation is required")]
        [MinLength(2, ErrorMessage = "Min length of designation is 2 characters")]
        public string Designation { get; set; }

        [Display(Name = "Has Dependents")]
        public bool HasDependents { get; set; } = false;

        public string DisplayForDependents
        {
            get
            {
                if (HasDependents)
                    return "Yes";

                return "No";
            }
        }

        public EmployeeRecord()
        {
            EmployeeId = 0;
            Address = string.Empty;
            Salary = 0;
            Age = 0;
            Address = string.Empty;
            EmployeeName = string.Empty;
            Designation = string.Empty;
            EmployeeGovtId = string.Empty;
            HasDependents = false;
        }
    }
}
3. EmployeeDBContext.cs - The context class allows you to perform database simple or complex operations to the database object Employee through the DbSet class. The OnModelCreating() method here isn't used for now since we are using the database approach. You may opt to use the code-first approach if you want to and perform migrations and update database commands.
public partial class EmployeeDBContext : DbContext
{
    public EmployeeDBContext()
    {

    }

    public EmployeeDBContext(DbContextOptions<EmployeeDBContext> options)
       : base(options)
    {
    }

    public virtual DbSet<Employee> Employees { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
            //optionsBuilder.UseSqlServer("Server=.;Database=ASPCoreTestDB;Integrated Security=True");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");

        modelBuilder.Entity<Employee>(entity =>
        {
            entity.ToTable("Employee");

            entity.Property(e => e.EmployeeId).HasColumnName("EmployeeID");

            entity.Property(e => e.Designation)
                .HasMaxLength(10)
                .IsUnicode(false);

            entity.Property(e => e.EmployeeGovtId)
                .HasMaxLength(50)
                .IsUnicode(false)
                .HasColumnName("EmployeeGovtID");

            entity.Property(e => e.EmployeeName)
                .HasMaxLength(200)
                .IsUnicode(false);

            entity.Property(e => e.Salary).HasColumnType("decimal(18, 2)");
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
4. IRepository.cs - the contract that defines set of methods that are used to communicate to the database.
public interface IRepository<T> where T : class
{
    T GetByID(int Id);
    IEnumerable<T> GetAll();
    IEnumerable<T> Find(Expression<Func<T, bool>> expression);
    void Add(T Entity);
    void Delete(T Delete);
    void Update(T Entity);
}
5. Repository.cs - the class that implements the set of methods that are defined in the IRepository interface.
public class Repository<T> : IRepository<T> where T : class
{
    private EmployeeDBContext _context;

    public Repository(EmployeeDBContext context)
    {
        this._context = context;
    }

    public void Add(T Entity)
    {
        _context.Set<T>().Add(Entity);
        _context.SaveChanges();
    }

    public void Delete(T Entity)
    {
        _context.Set<T>().Remove(Entity);
        _context.SaveChanges();
    }

    public IEnumerable<T> Find(Expression<Func<T, bool>> expression)
    {
        return _context.Set<T>().Where(expression);
    }

    public IEnumerable<T> GetAll()
    {
        return _context.Set<T>().AsNoTracking().ToList();
    }

    public T GetByID(int Id)
    {
        var entity = _context.Set<T>().Find(Id);
        _context.Entry(entity).State = EntityState.Detached;
        return entity;
    }

    public void Update(T Entity)
    {
        _context.Entry(Entity).State = EntityState.Modified;
        _context.Set<T>().Update(Entity);
        _context.SaveChanges();
    }
}
6. Program.cs - We need to setup the dependency injection for the repository and register the connection string so that we can inject the EmployeeDBContext in the Repository class constructor.
public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents()
        .AddInteractiveWebAssemblyComponents();

    builder.Services.AddDbContextFactory<EmployeeDBContext>(options =>
    options.UseSqlServer(
       builder.Configuration["ConnectionStrings:EmployeeContext"]
       ));

    builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

    //more codes here...
}

IV. Programming The Components

1. NavMenu.razor - Remove the other menu items and retain only Home menu link.
<div class="top-row ps-3 navbar navbar-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="">Blazor Crud App</a>
    </div>
</div>

<input type="checkbox" title="Navigation menu" class="navbar-toggler" />

<div class="nav-scrollable" onclick="document.querySelector('.navbar-toggler').click()">
    <nav class="flex-column">
        <div class="nav-item px-3">
            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
                <span class="bi bi-house-door-fill-nav-menu" aria-hidden="true"></span> Home
            </NavLink>
        </div>
    </nav>
</div>
2. App.razor - Add references to the font-awesome files.
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="bootstrap/bootstrap.min.css" />
    <link rel="stylesheet" href="app.css" />
    <link rel="stylesheet" href="BlazorCrudApp.styles.css" />
    <link rel="icon" type="image/png" href="favicon.png" />
    <link rel="stylesheet" href="/lib/font-awesome/css/fontawesome.css" />
    <link rel="stylesheet" href="/lib/font-awesome/css/regular.min.css" />
    <link rel="stylesheet" href="/lib/font-awesome/css/solid.min.css" />
    <HeadOutlet />
</head>
3. Home.razor - This component will show all employees registered through a table element. Each row has a link to update or show details of the employee. There's also a button to add new employee to the database. In the code section of the component, we need to inject the Repository to access the database methods.
@page "/"
@using BlazorCrudApp.Model
@using BlazorCrudApp.Repository

@rendermode InteractiveServer

<div class="container">
    <div class="row heading">
        <h3>Employee Government List</h3>
    </div>
    <br />
    <br />
    <div class="row">
        <div class="col-md-2" style="padding-left: 0px;">
            <a href="/employeeadd" class="btn btn-primary btn-sm mb-1">
                New Employee
            </a>
        </div>
        <div class="col-md-10" />
    </div>

    <div class="row tblEmployees">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Govt. Id</th>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Address</th>
                    <th>Salary</th>
                    <th>Designation</th>
                    <th>HasDependents</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                @if (true)
                {
                    foreach (var emp in EmployeeRecords)
                    {
                        <tr>
                            <td>@emp.EmployeeGovtId</td>
                            <td>@emp.EmployeeName</td>
                            <td>@emp.Age</td>
                            <td>@emp.Address</td>
                            <td>@emp.Salary</td>
                            <td>@emp.Designation</td>
                            <td>@emp.DisplayForDependents</td>
                            <td>
                                <a href="@($"employeeupdate/{emp.EmployeeId}")" title="Edit Employee" class="btn btn-info btn-sm mb-1">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="@($"employeedetail/{emp.EmployeeId}")" title="Employee Details" class="btn btn-primary btn-sm mb-1">
                                    <i class="fas fa-sticky-note"></i>
                                </a>
                            </td>
                        </tr>
                    }
                }
            </tbody>
        </table>
    </div>
</div>

@code {
    private string Title = "Employee Management";

    public List<EmployeeRecord> EmployeeRecords { get; set; }

    [Inject]
    public IRepository<Employee> Repository { get; set; }

    protected override void OnInitialized()
    {
        EmployeeRecords = new List<EmployeeRecord>();

        var result = Repository.GetAll();

        if (result.Count() > 0)
        {
            foreach (var item in result)
            {
                EmployeeRecords.Add(new EmployeeRecord()
                {
                    EmployeeId = item.EmployeeId,
                    Address = item.Address,
                    Age = item.Age,
                    Designation = item.Designation,
                    EmployeeGovtId = item.EmployeeGovtId,
                    EmployeeName = item.EmployeeName,
                    HasDependents = item.HasDependents.Value,
                    Salary = item.Salary,
                });
            }
        }
    }
}
Blazor Web App CRUD Project Using Visual Studio 2022, .NET 8 And Entity Framework Core
4. EmployeeAdd.razor - This components manages adding new employees to the database using EditForm component that renders a Form element to the browser. Within the EditForm component, lies several Input components like InputText, InputNumber and InputCheckbox of which the @bind-Value attribute is mapped to a property of the EmployeeRecord class. There are also buttons that performs different actions. One is to save the record. Another reset the form and navigate back to the Home component. In the code section of the component, we need to inject the Repository class to access the database methods and the NavigationManager class to utilize the NavigateTo() method which we can pass the route back to the Home page. Lastly, there's the OnEmployeeSubmit() method that retrieves the values of the EmployeeRecord object properties and assign them to the Employee object which is used by the save functionality of the DbContext.
@page "/employeeadd"
@using BlazorCrudApp.Model
@using BlazorCrudApp.Repository

@rendermode InteractiveServer

<PageTitle>@Title</PageTitle>

<div class="container">
    <div class="row">
        @if (!string.IsNullOrEmpty(StatusMessage))
        {
            <div class="alert @StatusClass statusMessage">@StatusMessage</div>
        }
    </div>

    <div class="row">
        <h3>Add Employee</h3>
    </div>

    <EditForm Enhance
              Model="EmployeeRecord"
              OnValidSubmit="OnEmployeeSubmit"
              FormName="frmAddEmployee">

        <div class="row mb-3">
            <label for="govtid" class="col-form-label col-md-3">Govt ID: </label>
            <div class="col-md-8">
                <InputText id="govtid" class="form-control col-md-8" @bind-Value="@EmployeeRecord.EmployeeGovtId" placeholder="Enter govt. id"></InputText>
            </div>
        </div>

        <div class="row mb-3">
            <label for="govtid" class="col-form-label col-md-3">Name: </label>
            <div class="col-md-8">
                <InputText id="govtid" class="form-control col-md-8" @bind-Value="@EmployeeRecord.EmployeeName" placeholder="Enter employee name"></InputText>
            </div>
        </div>

        <div class="row mb-3">
            <label for="age" class="col-form-label col-md-3">Age: </label>
            <div class="col-md-8">
                <InputNumber id="age" class="form-control col-md-8" @bind-Value="@EmployeeRecord.Age"></InputNumber>
            </div>
        </div>

        <div class="row mb-3">
            <label for="address" class="col-form-label col-md-3">Address: </label>
            <div class="col-md-8">
                <InputText id="address" class="form-control col-md-8" @bind-Value="@EmployeeRecord.Address" placeholder="Enter employee address"></InputText>
            </div>
        </div>

        <div class="row mb-3">
            <label for="salary" class="col-form-label col-md-3">Salary: </label>
            <div class="col-md-8">
                <InputNumber id="salary" class="form-control col-md-8" @bind-Value="@EmployeeRecord.Salary"></InputNumber>
            </div>
        </div>

        <div class="row mb-3">
            <label for="designation" class="col-form-label col-md-3">Designation: </label>
            <div class="col-md-8">
                <InputText id="designation" class="form-control col-md-8" @bind-Value="@EmployeeRecord.Designation" placeholder="Enter employee designation"></InputText>
            </div>
        </div>

        <div class="row mb-3">
            <label for="hasDependents" class="col-form-label col-md-3">Has Dependents?: </label>
            <div class="col-md-2">
                <InputCheckbox id="hasDependents" class="form-check" style="height:20px; width:20px;" @bind-Value="@EmployeeRecord.HasDependents"></InputCheckbox>
            </div>
        </div>

        <div class="row">
            <div class="col-md-1">
                <button type="submit" class="btn btn-primary submitButton">Save</button>
            </div>
            <div class="col-md-1">
                <button type="reset" class="btn btn-primary submitButton" @onclick="@Reset">Clear</button>
            </div>
            <div class="col-md-1">
                <button type="button" class="btn btn-info" @onclick="@NavigateToMain">Home</button>
            </div>
        </div>
    </EditForm>
</div>

@code {
    protected string StatusMessage = string.Empty;
    protected string StatusClass = string.Empty;

    private string Title = "Employee Entry";

    [SupplyParameterFromForm]
    public EmployeeRecord EmployeeRecord { get; set; }

    [Inject]
    public IRepository<Employee> Repository { get; set; }

    [Inject]
    public NavigationManager NavigationManager { get; set; }

    protected override void OnInitialized()
    {
        StatusClass = string.Empty;
        StatusMessage = string.Empty;
        EmployeeRecord = new EmployeeRecord();
    }

    protected void OnEmployeeSubmit()
    {
        Employee empObject = new Employee();

        empObject.Address = EmployeeRecord.Address;
        empObject.Age = EmployeeRecord.Age;
        empObject.Designation = EmployeeRecord.Designation;
        empObject.EmployeeGovtId = EmployeeRecord.EmployeeGovtId;
        empObject.EmployeeName = EmployeeRecord.EmployeeName;
        empObject.HasDependents = EmployeeRecord.HasDependents;
        empObject.Salary = EmployeeRecord.Salary;

        Repository.Add(empObject);

        StatusClass = "alert-success";
        StatusMessage = "Employee successfully added to the database.";
        EmployeeRecord = new EmployeeRecord();
    }

    protected void Reset()
    {
        StatusClass = string.Empty;
        StatusMessage = string.Empty;
        EmployeeRecord = new EmployeeRecord();
    }

    protected void NavigateToMain()
    {
        NavigationManager.NavigateTo("/");
    }
}
Blazor Web App CRUD Project Using Visual Studio 2022, .NET 8 And Entity Framework Core
5. EmployeeUpdate.razor - This components manages updating records of existing employees from the database. This also utilize the EditForm component and has identical Input controls and structure like the EmployeeAdd component. The OnInitialized() method will call the LoadEmployee() method that searches the database for a particular ID and stores the result back to the EmployeeRecord object. Upon saving, the property values of the EmployeeRecord will be assigned to an Employee object that is passed as parameter to the Update() method of the Repository class thus updating the employee details.
@page "/employeeupdate/{EmployeeId:int}"
@using BlazorCrudApp.Model
@using BlazorCrudApp.Repository

@rendermode InteractiveServer

<div class="container">
    <div class="row">
        @if (!string.IsNullOrEmpty(StatusMessage))
        {
            <div class="alert @StatusClass statusMessage">@StatusMessage</div>
        }
    </div>

    <div class="row">
        <h3>Update Employee</h3>
    </div>

    <EditForm Enhance
              Model="EmployeeRecord"
              OnValidSubmit="OnEmployeeSubmit"
              FormName="frmEditEmployee">

        <div class="row mb-3">
            <label for="govtid" class="col-form-label col-md-3">Govt ID: </label>
            <div class="col-md-8">
                <InputText id="govtid" class="form-control col-md-8" @bind-Value="@EmployeeRecord.EmployeeGovtId" placeholder="Enter govt. id"></InputText>
            </div>
        </div>

        <div class="row mb-3">
            <label for="govtid" class="col-form-label col-md-3">Name: </label>
            <div class="col-md-8">
                <InputText id="govtid" class="form-control col-md-8" @bind-Value="@EmployeeRecord.EmployeeName" placeholder="Enter employee name"></InputText>
            </div>
        </div>

        <div class="row mb-3">
            <label for="age" class="col-form-label col-md-3">Age: </label>
            <div class="col-md-8">
                <InputNumber id="age" class="form-control col-md-8" @bind-Value="@EmployeeRecord.Age"></InputNumber>
            </div>
        </div>

        <div class="row mb-3">
            <label for="address" class="col-form-label col-md-3">Address: </label>
            <div class="col-md-8">
                <InputText id="address" class="form-control col-md-8" @bind-Value="@EmployeeRecord.Address" placeholder="Enter employee address"></InputText>
            </div>
        </div>

        <div class="row mb-3">
            <label for="salary" class="col-form-label col-md-3">Salary: </label>
            <div class="col-md-8">
                <InputNumber id="salary" class="form-control col-md-8" @bind-Value="@EmployeeRecord.Salary"></InputNumber>
            </div>
        </div>

        <div class="row mb-3">
            <label for="designation" class="col-form-label col-md-3">Designation: </label>
            <div class="col-md-8">
                <InputText id="designation" class="form-control col-md-8" @bind-Value="@EmployeeRecord.Designation" placeholder="Enter employee designation"></InputText>
            </div>
        </div>

        <div class="row mb-3">
            <label for="hasDependents" class="col-form-label col-md-3">Has Dependents?: </label>
            <div class="col-md-2">
                <InputCheckbox id="hasDependents" class="form-check" style="height:20px; width:20px;" @bind-Value="@EmployeeRecord.HasDependents"></InputCheckbox>
            </div>
        </div>

        <div class="row">
            <div class="col-md-1">
                <button type="submit" class="btn btn-primary submitButton">Save</button>
            </div>
            <div class="col-md-1">
                <button type="reset" class="btn btn-primary submitButton" @onclick="@Reset">Clear</button>
            </div>
            <div class="col-md-1">
                <button type="button" class="btn btn-info" @onclick="@NavigateToMain">Home</button>
            </div>
        </div>
    </EditForm>
</div>

@code {
    [Parameter]
    public int EmployeeId { get; set; }

    protected string StatusMessage = string.Empty;
    protected string StatusClass = string.Empty;

    private string Title = "Employee Update";

    [SupplyParameterFromForm]
    public EmployeeRecord EmployeeRecord { get; set; }

    [Inject]
    public NavigationManager NavigationManager { get; set; }

    [Inject]
    public IRepository<Employee> Repository { get; set; }

    protected override void OnInitialized()
    {
        StatusClass = string.Empty;
        StatusMessage = string.Empty;
        LoadEmployee();
    }

    protected void OnEmployeeSubmit()
    {
        Employee empObject = new Employee();

        empObject.EmployeeId = EmployeeRecord.EmployeeId;
        empObject.Address = EmployeeRecord.Address;
        empObject.Age = EmployeeRecord.Age;
        empObject.Designation = EmployeeRecord.Designation;
        empObject.EmployeeGovtId = EmployeeRecord.EmployeeGovtId;
        empObject.EmployeeName = EmployeeRecord.EmployeeName;
        empObject.HasDependents = EmployeeRecord.HasDependents;
        empObject.Salary = EmployeeRecord.Salary;

        Repository.Update(empObject);
        StatusClass = "alert-success";
        StatusMessage = "Employee successfully updated.";
        LoadEmployee();
    }

    private void LoadEmployee()
    {
        Employee empObject = new Employee();
        EmployeeRecord = new EmployeeRecord();

        empObject = new Employee();
        empObject = Repository.GetByID(EmployeeId);
        EmployeeRecord.EmployeeId = empObject.EmployeeId;
        EmployeeRecord.Address = empObject.Address;
        EmployeeRecord.Age = empObject.Age;
        EmployeeRecord.Designation = empObject.Designation;
        EmployeeRecord.EmployeeGovtId = empObject.EmployeeGovtId;
        EmployeeRecord.EmployeeName = empObject.EmployeeName;
        EmployeeRecord.HasDependents = empObject.HasDependents.Value;
        EmployeeRecord.Salary = empObject.Salary;
    }

    protected void Reset()
    {
        StatusClass = string.Empty;
        StatusMessage = string.Empty;
        EmployeeRecord = new EmployeeRecord();
        EmployeeRecord.EmployeeId = EmployeeId;
    }

    protected void NavigateToMain()
    {
        NavigationManager.NavigateTo("/");
    }
}
Blazor Web App CRUD Project Using Visual Studio 2022, .NET 8 And Entity Framework Core
6. EmployeeDetails.razor - The EmployeeDetails component will show the attributes of an employee through the OnInitialized() method. It has also a delete method that permanently removes the employee record.
@page "/employeedetail/{EmployeeId:int}"

@using BlazorCrudApp.Model
@using BlazorCrudApp.Repository

@rendermode InteractiveServer

<div class="container">
    <div class="row heading">
        <h3>Employee Details</h3>
    </div>
    <hr />
    <br />
    <div class="row">
        <div class="row mb-2">
            <label class="col-sm-2 col-form-label">Govt ID</label>
            <div class="col-sm-10">
                <label type="text" class="form-control">@EmployeeRecord.EmployeeGovtId</label>
            </div>
        </div>

        <div class="row mb-2">
            <label class="col-sm-2 col-form-label">Employee Name</label>
            <div class="col-sm-10">
                <label type="text" class="form-control">@EmployeeRecord.EmployeeName</label>
            </div>
        </div>

        <div class="row mb-2">
            <label class="col-sm-2 col-form-label">Age</label>
            <div class="col-sm-10">
                <label type="text" class="form-control">@EmployeeRecord.Age</label>
            </div>
        </div>

        <div class="row mb-2">
            <label class="col-sm-2 col-form-label">Address</label>
            <div class="col-sm-10">
                <label type="text" class="form-control">@EmployeeRecord.Address</label>
            </div>
        </div>

        <div class="row mb-2">
            <label class="col-sm-2 col-form-label">Salary</label>
            <div class="col-sm-10">
                <label type="text" class="form-control">@EmployeeRecord.Salary</label>
            </div>
        </div>

        <div class="row mb-2">
            <label class="col-sm-2 col-form-label">Designation</label>
            <div class="col-sm-10">
                <label type="text" class="form-control">@EmployeeRecord.Designation</label>
            </div>
        </div>

        <div class="row mb-2">
            <label class="col-sm-2 col-form-label">HasDependents</label>
            <div class="col-sm-10">
                <label type="text" class="form-control">@EmployeeRecord.DisplayForDependents</label>
            </div>
        </div>

        <div class="row">
            <div class="col-md-1">
                <button type="button" class="btn btn-primary" @onclick="@NavigateToMain">Home</button>
            </div>
            <div class="col-md-3">
                <button type="button" class="btn btn-danger" @onclick="@DeleteEmployee">Delete Employee</button>
            </div>
        </div>
    </div>
</div>

@code {
    [Parameter]
    public int EmployeeId { get; set; }

    public EmployeeRecord EmployeeRecord { get; set; }

    [Inject]
    public NavigationManager NavigationManager { get; set; }

    [Inject]
    public IRepository<Employee> Repository { get; set; }

    protected override void OnInitialized()
    {
        Employee employee = new Employee();
        EmployeeRecord = new EmployeeRecord();
        employee = Repository.GetByID(EmployeeId);

        EmployeeRecord.EmployeeId = employee.EmployeeId;
        EmployeeRecord.Salary = employee.Salary;
        EmployeeRecord.Address = employee.Address;
        EmployeeRecord.EmployeeGovtId = employee.EmployeeGovtId;
        EmployeeRecord.EmployeeName = employee.EmployeeName;
        EmployeeRecord.Age = employee.Age;
        EmployeeRecord.Designation = employee.Designation;
        EmployeeRecord.HasDependents = employee.HasDependents.Value;
    }

    protected void NavigateToMain()
    {
        NavigationManager.NavigateTo("/");
    }

    protected void DeleteEmployee()
    {
        Employee employee = new Employee();
        employee = Repository.GetByID(EmployeeId);
        Repository.Delete(employee);
        NavigationManager.NavigateTo("/");
    }
}
Blazor Web App CRUD Project Using Visual Studio 2022, .NET 8 And Entity Framework Core



That's It!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input