Tutorial - Employee Management System - Part 1
EMS: Displaying a Static Employee List in Blazor Server
This guide will walk you through setting up a Blazor Server application to display a static list of employees, preparing the foundation for future integration with a REST API.
Project Structure Overview:
- EmployeeManagement.Models: A .NET Standard Class Library project that will contain our data model classes (Employee, Department, Gender). This project can be shared across different layers (e.g., API, Web).
- EmployeeManagement.Web: A Blazor Server project that will serve as our web application, responsible for displaying and interacting with employee data.
Step-by-Step Tutorial Guide
Part 1: Create the Model Project (EmployeeManagement.Models)
- Open Visual Studio: Launch Visual Studio 2022 (or a compatible version).
- Create a New Project:
- Click "Create a new project".
- Search for "Class Library" and select "Class Library (.NET Standard)". Click "Next".
- Project name:
EmployeeManagement.Models - Location: Choose a suitable directory for your solution.
- Solution name:
BlazorTutorial(or any name you prefer for your solution). - Click "Next".
- Framework:
.NET Core 6.0 or +(or a compatible version). - Click "Create".
- Define Model Classes:
- In the
EmployeeManagement.Modelsproject, delete the defaultClass1.csfile. - Right-click on the
EmployeeManagement.Modelsproject in Solution Explorer, select "Add" -> "Class...". - Add the following three classes (create each one separately):
Employee.csGender.csDepartment.cs
- In the
- Employee.cs:
- Gender.cs:
- Department.cs:
- Build the project: Right-click on
EmployeeManagement.Modelsand select "Build". Ensure there are no errors.
using System; using System.Collections.Generic; using System.Text; namespace EmployeeManagement.Models { public class Employee { public int EmployeeId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public DateTime DateOfBrith { get; set; } public Gender Gender { get; set; } public Department Department { get; set; } // Note: This will be null in our current static data setup public string PhotoPath { get; set; } } }
namespace EmployeeManagement.Models { public enum Gender { Male, Female, Other } }
namespace EmployeeManagement.Models { public class Department { public int DepartmentId { get; set; } public string DepartmentName { get; set; } } }
Part 2: Create the Blazor Web Project (EmployeeManagement.Web)
- Add a New Project to the Solution:
- Right-click on your
BlazorTutorialsolution in Solution Explorer, select "Add" -> "New Project...". - Search for "Blazor Server App" and select it. Click "Next".
- Project name:
EmployeeManagement.Web - Location: Ensure it's in the same solution directory.
- Click "Next".
- Framework:
.NET 8.0 (Long Term Support)(or the latest stable LTS version). - Authentication type: "None".
- Click "Create".
- Right-click on your
- Add Project Reference:
- In the
EmployeeManagement.Webproject, right-click on "Dependencies", select "Add Project Reference...". - In the "Reference Manager" dialog, go to "Projects" -> "Solution".
- Check the box next to
EmployeeManagement.Models. - Click "OK".
- In the
- Set as Startup Project:
- Right-click on the
EmployeeManagement.Webproject in Solution Explorer. - Select "Set as Startup Project".
- Right-click on the
Part 3: Configure the Web Project (EmployeeManagement.Web)
Now, let's make the necessary changes to the Program.cs file and delete some default Blazor files.
- Delete Unnecessary Files and Folders:
- In your
EmployeeManagement.Webproject, right-click and "Delete" the following files and folders: Datafolder: (This folder containsWeatherForecast.csandWeatherForecastService.cs, which we won't be using).Pages/Counter.razorPages/FetchData.razorPages/Index.razor(We will recreate our ownIndex.razorlater, inheriting fromEmployeeListBase.cs)Shared/SurveyPrompt.razor
- In your
- Modify Program.cs:
- Open the
Program.csfile in yourEmployeeManagement.Webproject. - Remove the
usingstatement:
- Open the
- Remove the service registration for
WeatherForecastService: - Find and remove the line:
- Your
Program.csshould now look something like this (exact comments/structure might vary slightly based on template version, but the key removals are what's important):
// Remove this line if it exists (it likely will if you started with a default template) // using EmployeeManagement.Web.Data;
// Remove this line // builder.Services.AddSingleton<WeatherForecastService>();
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); // The line for WeatherForecastService should be removed from here. var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); app.Run();
Part 4: Create the Employee List Component
We'll create two files for our EmployeeList component: the .razor file for the UI and the .cs file for the C# logic (code-behind).
- Add EmployeeList.razor:
- In the
EmployeeManagement.Webproject, right-click on thePagesfolder, select "Add" -> "Razor Component...". - Name it
EmployeeList.razor. - Replace its content with the following:
- In the
- Explanation:
@page "/": This makesEmployeeList.razorthe default component rendered when the application loads at the root URL.@inherits EmployeeListBase: This links the UI component to its C# code-behind class,EmployeeListBase.- The
@if (Employees == null)block handles the loading state, displaying a spinner until the employee data is loaded. - The
@foreachloop iterates through theEmployeescollection (which will be provided byEmployeeListBase) to display each employee as a Bootstrap card. - Add EmployeeListBase.cs (Code-Behind):
- In the
EmployeeManagement.Webproject, right-click on thePagesfolder, select "Add" -> "Class...". - Name it
EmployeeListBase.cs. - Replace its content with the following:
- In the
- Explanation:
@inherits ComponentBase: This class inherits from Blazor'sComponentBase, providing lifecycle methods.Employees { get; set; }: This property will hold the list of employees that theEmployeeList.razorUI binds to.protected override async Task OnInitializedAsync(): This lifecycle method is called when the component is initialized. We useasync/awaitandTask.Run()to simulate an asynchronous data loading operation, which is typical when fetching data from a server.LoadEmployees(): This private method currently contains our hardcoded employee data. TheThread.Sleep(2000)simulates a 2-second delay to show the loading spinner.
@page "/" @inherits EmployeeListBase <h3>Employee List</h3> @if (Employees == null) { <div class="spinner"></div> } @else { <div class="card-deck"> @foreach (var employee in Employees) { <div class="card m-3" style="min-width: 18rem; max-width:30.5%;"> <div class="card-header"> <h3>@employee.FirstName @employee.LastName</h3> </div> <img class="card-img-top imageThumbnail" src="@employee.PhotoPath" /> <div class="card-footer text-center"> <a href="#" class="btn btn-primary m-1">View</a> <a href="#" class="btn btn-primary m-1">Edit</a> <a href="#" class="btn btn-danger m-1">Delete</a> </div> </div> } </div> }
using EmployeeManagement.Models; using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace EmployeeManagement.Web.Pages { public class EmployeeListBase : ComponentBase { public IEnumerable<Employee> Employees { get; set; } protected override async Task OnInitializedAsync() { // Simulate an asynchronous operation (like fetching data from an API) await Task.Run(LoadEmployees); } private void LoadEmployees() { // Simulate network latency System.Threading.Thread.Sleep(2000); // Hardcoded Employee Data Employee e1 = new Employee { EmployeeId = 1, FirstName = "Raushan", LastName = "Ranjan", Email = "Raushan@rrtech.com", DateOfBrith = new DateTime(1998, 11, 11), Gender = Gender.Male, // Department = new Department { DepartmentId = 1, DepartmentName = "IT" }, // Commented out as Department isn't fully set up in static data PhotoPath = "images/raushan.jpg" }; Employee e2 = new Employee { EmployeeId = 2, FirstName = "Sam", LastName = "Galloway", Email = "Sam@rrtech.com", DateOfBrith = new DateTime(1981, 12, 22), Gender = Gender.Male, // Department = new Department { DepartmentId = 2, DepartmentName = "HR" }, PhotoPath = "images/john.png" }; Employee e3 = new Employee { EmployeeId = 3, FirstName = "Pratibha", LastName = "Poddar", Email = "pratibha@rrtech.com", DateOfBrith = new DateTime(2000, 07, 11), Gender = Gender.Female, // Department = new Department { DepartmentId = 1, DepartmentName = "IT" }, PhotoPath = "images/pratibha.png" }; Employee e4 = new Employee { EmployeeId = 4, // Corrected EmployeeId for uniqueness FirstName = "Sara", LastName = "Longway", Email = "sara@rrtech.com", DateOfBrith = new DateTime(1982, 9, 23), Gender = Gender.Female, // Department = new Department { DepartmentId = 3, DepartmentName = "Payroll" }, PhotoPath = "images/mary.png" }; Employees = new List<Employee> { e1, e3, e2, e4 }; // You can arrange the order as you like } } }
Part 5: Update Layout and Styling
- Modify Shared/MainLayout.razor:
- Open
Shared/MainLayout.razor. - Locate the
divelement that wraps@Body. - Add the Bootstrap
containerclass to it.
- Open
- Before:
- After:
- Add CSS to wwwroot/css/site.css:
- Open
wwwroot/css/site.css. - Add the following CSS rules for image styling and the loading spinner:
- Open
<div class="main"> <div class="content px-4"> @Body </div> </div>
<div class="main"> <div class="content px-4 container"> @Body </div> </div>
.imageThumbnail {
height: 200px;
width: auto;
}
.spinner {
border: 16px solid silver;
border-top: 16px solid #337AB7; /* Bootstrap primary blue */
border-radius: 50%;
width: 80px;
height: 80px;
animation: spin 700ms linear infinite;
top: 40%;
left: 55%;
position: absolute;
z-index: 1000; /* Ensure it's above other content */
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
Part 6: Add Images
- Download Images:
- Download the four employee images (e.g.,
raushan.jpg,john.png,pratibha.png,mary.png). You can use placeholder images if you don't have these specific ones. Make sure their filenames match what's used inEmployeeListBase.cs.
- Download the four employee images (e.g.,
- Place Images in wwwroot/images:
- In your
EmployeeManagement.Webproject, expand thewwwrootfolder. - If an
imagesfolder doesn't exist, right-click onwwwroot, select "Add" -> "New Folder", and name itimages. - Drag and drop (or copy and paste) your downloaded images into the
wwwroot/imagesfolder.
- In your
Part 7: Run the Application
- Build the Solution:
- Go to "Build" -> "Build Solution" (or press
Ctrl+Shift+B). - Ensure there are no build errors.
- Go to "Build" -> "Build Solution" (or press
- Run the Application:
- Press
F5or click the "Run" button (green play icon) in Visual Studio. - You should now see your Blazor application launch in a web browser. Initially, you'll see a loading spinner for about 2 seconds, and then the list of employees will appear, styled with Bootstrap cards and their respective images.
- Press
Comments
Post a Comment