Back to: ASP.NET Core Tutorials For Beginners and Professionals
Employee Portal Application Development using ASP.NET Core MVC
We will develop an application to efficiently manage employee data in a structured manner. This Employee Portal will enable users to easily add new employees, view detailed information about existing employees, update employee records, and delete employees as needed.
The design will focus on creating user-friendly interfaces that ensure smooth navigation and interaction. This will enable the admin to manage employee information quickly and effectively. Below, we will outline the various pages that will be developed as part of this application. Let’s first begin by exploring the different pages and features that will be part of this Employee Portal application.
Employee List or Index Page:
The Employee List Page functions as the central dashboard of your Employee Portal application. It provides a clean, user-friendly interface for viewing, filtering, and managing employee records efficiently. The page is designed to handle a large volume of data by incorporating filtering and pagination, ensuring users can quickly locate and act upon specific employee information. The List or Index page will look like the one below:

Features:
- Displays a table with employee information like Name, Email, Position, Department, Gender, and Employee Type.
- Allows users to filter employees by department, employee type, and name.
- Includes pagination controls to navigate through multiple pages of employee records.
- Users can perform actions like viewing details, updating, and deleting employees from this page.
Employee Create Page:
The Create Employee Page is designed to enable admins to add new employee records into the system. The interface focuses on simplicity and clarity, providing a well-structured form that collects all necessary employee information to ensure completeness and accuracy. The Create Employee page will look like the one below:

Features:
- Presents a form for entering employee details, including Full Name, Email, Position, Department, Hire Date, Date of Birth, Employee Type, Gender, and Salary.
- Includes validation to ensure all required fields are filled out correctly before submission.
- It also includes a Back button, in case the user doesn’t want to create a new employee and instead returns to the List page.
After submitting the form, the new employee is added to the system, and the user is redirected to the Success Page.
Employee Success Page:
The Success Page serves as a confirmation screen, informing the admin that a new employee has been successfully created and recorded in the system. It also provides a clear and concise summary of the employee’s key details for immediate review, enhancing transparency and user confidence. The Success page will look like the one below:

Features:
- Displays a summary of the employee’s details that were entered on the Create Page.
- Offers options to either create another employee or return to the Employee List page.
- This page reassures users that their actions were successful and provides easy navigation for further actions.
Employee Details Page:
The Details Page provides a comprehensive and well-organized display of a selected employee’s information. It serves as a dedicated view where the admin can verify all stored data for an individual employee, supporting informed decision-making and efficient management. The Details page will look like the one below:

Features:
- Displays all information about the selected employee, such as Full Name, Email, Position, Department, Hire Date, Date of Birth, Employee Type, Gender, and Salary.
- Allows users to navigate back to the List Page or proceed to update or delete the employee’s information.
- This page is essential for users who need to verify or review detailed employee information before making decisions.
Employee Update Page:
The Update Employee Page enables administrators to modify the details of an existing employee efficiently. The interface is designed to facilitate easy editing by presenting the current data in a pre-filled form, allowing users to make necessary changes and save them quickly. The Update page will look like the one below:

Features:
- Presents a form similar to the Create Page but pre-filled with the employee’s existing data.
- Users can update any of the employee’s details, including Full Name, Email, Position, Department, Hire Date, Date of Birth, Employee Type, Gender, and Salary.
- After submitting the form, the updated information is saved, and the user is redirected back to the List Page to confirm the changes.
Employee Delete Page:
The Delete Page serves as a crucial checkpoint in the employee management workflow, providing a clear and informative confirmation prompt before permanently removing an employee’s record. This ensures that deletions are intentional and prevents accidental data loss. The Delete page will look like the one below:

Features:
- Presents a confirmation prompt with details of the employee to be deleted, ensuring users are aware of the action they are about to take.
- Users can confirm the deletion, which permanently removes the employee from the system, or cancel the action to return to the List Page.
- This page is essential for maintaining data integrity and preventing accidental deletions.
Creating a new ASP.NET Core MVC Project:
Let us proceed and implement this application step by step using ASP.NET Core MVC. First, create a new ASP.NET Core Project using the Model-View-Controller template and provide the project name as EmployeePortal.
Add EF Core NuGet Packages
Next, add the required EF Core packages to your project via NuGet:
- Install-Package Microsoft.EntityFrameworkCore.SqlServer
- Install-Package Microsoft.EntityFrameworkCore.Tools
These packages enable us to utilize EF Core for object-relational mapping (ORM), database migrations, and SQL Server as the database provider.
EmployeeType Entity:
Create a class file named EmployeeType.cs within the Models folder, and then copy and paste the following code. This class represents various types of employment, including Permanent, Temporary, Contract, and Intern. It helps categorize employees based on their employment status and tracks whether each type is active.
namespace EmployeePortal.Models
public class EmployeeType
public int Id { get; set; }
public string Name { get; set; } = null!;
public bool IsActive { get; set; }
public List<Employee>? Employees { get; set; }
namespace EmployeePortal.Models
{
public class EmployeeType
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public bool IsActive { get; set; }
public List<Employee>? Employees { get; set; }
}
}
namespace EmployeePortal.Models
{
public class EmployeeType
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public bool IsActive { get; set; }
public List<Employee>? Employees { get; set; }
}
}
Department Entity:
Next, create another class file named Department.cs within the Models folder, and then copy and paste the following code. This class defines the various departments within the organization, including IT, HR, Sales, and Administration. It organizes employees and designations by department and includes an active status to manage department availability.
namespace EmployeePortal.Models
public int Id { get; set; }
public string Name { get; set; } = null!;
public bool IsActive { get; set; }
public ICollection<Designation>? Designations { get; set; } = new List<Designation>();
public List<Employee>? Employees { get; set; }
namespace EmployeePortal.Models
{
public class Department
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public bool IsActive { get; set; }
public ICollection<Designation>? Designations { get; set; } = new List<Designation>();
public List<Employee>? Employees { get; set; }
}
}
namespace EmployeePortal.Models
{
public class Department
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public bool IsActive { get; set; }
public ICollection<Designation>? Designations { get; set; } = new List<Designation>();
public List<Employee>? Employees { get; set; }
}
}
Designation Entity:
Next, create another class file named Designation.cs within the Models folder, and then copy and paste the following code. This class represents job titles or positions within departments, such as Software Developer or HR Manager. Each designation belongs to a specific department and can be activated or deactivated.
namespace EmployeePortal.Models
public int Id { get; set; }
public string Name { get; set; } = null!;
public int DepartmentId { get; set; }
public Department Department { get; set; } = null!;
public bool IsActive { get; set; }
namespace EmployeePortal.Models
{
public class Designation
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public int DepartmentId { get; set; }
public Department Department { get; set; } = null!;
public bool IsActive { get; set; }
}
}
namespace EmployeePortal.Models
{
public class Designation
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public int DepartmentId { get; set; }
public Department Department { get; set; } = null!;
public bool IsActive { get; set; }
}
}
Employee Entity:
Next, create a class file named Employee.cs within the Models folder and then copy and paste the following code. This class represents an employee with all their relevant details like name, email, department, designation, hire date, birth date, employment type, gender, and salary. It uses validation to ensure data integrity.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EmployeePortal.Models
public int Id { get; set; }
[Required(ErrorMessage = "Full Name is required")]
[StringLength(100, ErrorMessage = "Full Name cannot be longer than 100 characters")]
public string FullName { get; set; } = null!;
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; } = null!;
[Required(ErrorMessage = "Department is required")]
public int DepartmentId { get; set; }
public Department Department { get; set; } = null!;
[Required(ErrorMessage = "Designation is required")]
public int DesignationId { get; set; }
public Designation Designation { get; set; } = null!;
[Required(ErrorMessage = "Hire Date is required")]
[DataType(DataType.Date)]
public DateTime HireDate { get; set; }
[Required(ErrorMessage = "Date of Birth is required")]
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
[Required(ErrorMessage = "Employee Type is required")]
public int EmployeeTypeId { get; set; }
public EmployeeType EmployeeType { get; set; } = null!;
[Required(ErrorMessage = "Gender is required")]
[StringLength(6, ErrorMessage = "Gender should be Male, Female, or Other")]
public string Gender { get; set; } = null!;
[Required(ErrorMessage = "Salary is required")]
[Range(0, double.MaxValue, ErrorMessage = "Salary must be a positive number")]
[Column(TypeName = "decimal(18,2)")]
public decimal Salary { get; set; }
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EmployeePortal.Models
{
public class Employee
{
public int Id { get; set; }
[Required(ErrorMessage = "Full Name is required")]
[StringLength(100, ErrorMessage = "Full Name cannot be longer than 100 characters")]
public string FullName { get; set; } = null!;
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; } = null!;
[Required(ErrorMessage = "Department is required")]
public int DepartmentId { get; set; }
public Department Department { get; set; } = null!;
[Required(ErrorMessage = "Designation is required")]
public int DesignationId { get; set; }
public Designation Designation { get; set; } = null!;
[Required(ErrorMessage = "Hire Date is required")]
[DataType(DataType.Date)]
public DateTime HireDate { get; set; }
[Required(ErrorMessage = "Date of Birth is required")]
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
[Required(ErrorMessage = "Employee Type is required")]
public int EmployeeTypeId { get; set; }
public EmployeeType EmployeeType { get; set; } = null!;
[Required(ErrorMessage = "Gender is required")]
[StringLength(6, ErrorMessage = "Gender should be Male, Female, or Other")]
public string Gender { get; set; } = null!;
[Required(ErrorMessage = "Salary is required")]
[Range(0, double.MaxValue, ErrorMessage = "Salary must be a positive number")]
[Column(TypeName = "decimal(18,2)")]
public decimal Salary { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EmployeePortal.Models
{
public class Employee
{
public int Id { get; set; }
[Required(ErrorMessage = "Full Name is required")]
[StringLength(100, ErrorMessage = "Full Name cannot be longer than 100 characters")]
public string FullName { get; set; } = null!;
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; } = null!;
[Required(ErrorMessage = "Department is required")]
public int DepartmentId { get; set; }
public Department Department { get; set; } = null!;
[Required(ErrorMessage = "Designation is required")]
public int DesignationId { get; set; }
public Designation Designation { get; set; } = null!;
[Required(ErrorMessage = "Hire Date is required")]
[DataType(DataType.Date)]
public DateTime HireDate { get; set; }
[Required(ErrorMessage = "Date of Birth is required")]
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
[Required(ErrorMessage = "Employee Type is required")]
public int EmployeeTypeId { get; set; }
public EmployeeType EmployeeType { get; set; } = null!;
[Required(ErrorMessage = "Gender is required")]
[StringLength(6, ErrorMessage = "Gender should be Male, Female, or Other")]
public string Gender { get; set; } = null!;
[Required(ErrorMessage = "Salary is required")]
[Range(0, double.MaxValue, ErrorMessage = "Salary must be a positive number")]
[Column(TypeName = "decimal(18,2)")]
public decimal Salary { get; set; }
}
}
Employee List View Model:
Next, create a class file named EmployeeListViewModel.cs within the ViewModels (create this folder on the project root directory) folder, and then copy and paste the following code. This view model is used to pass employee data to the list view. It includes the list of employees, paging information, search terms, selected filters, and lists of departments and employee types for dropdowns.
using EmployeePortal.Models;
namespace EmployeePortal.ViewModels
public class EmployeeListViewModel
public List<Employee>? Employees { get; set; }
public int TotalPages { get; set; }
public string? SearchTerm { get; set; }
public int? SelectedDepartmentId { get; set; }
public int? SelectedEmployeeTypeId { get; set; }
public int PageSize { get; set; }
public int PageNumber { get; set; }
public int Total { get; set; }
public List<Department>? Departments { get; set; }
public List<EmployeeType>? EmployeeTypes { get; set; }
using EmployeePortal.Models;
namespace EmployeePortal.ViewModels
{
public class EmployeeListViewModel
{
public List<Employee>? Employees { get; set; }
public int TotalPages { get; set; }
public string? SearchTerm { get; set; }
public int? SelectedDepartmentId { get; set; }
public int? SelectedEmployeeTypeId { get; set; }
public int PageSize { get; set; }
public int PageNumber { get; set; }
public int Total { get; set; }
public List<Department>? Departments { get; set; }
public List<EmployeeType>? EmployeeTypes { get; set; }
}
}
using EmployeePortal.Models;
namespace EmployeePortal.ViewModels
{
public class EmployeeListViewModel
{
public List<Employee>? Employees { get; set; }
public int TotalPages { get; set; }
public string? SearchTerm { get; set; }
public int? SelectedDepartmentId { get; set; }
public int? SelectedEmployeeTypeId { get; set; }
public int PageSize { get; set; }
public int PageNumber { get; set; }
public int Total { get; set; }
public List<Department>? Departments { get; set; }
public List<EmployeeType>? EmployeeTypes { get; set; }
}
}
Employee Create Update View Model:
Next, create a class file named EmployeeCreateUpdateViewModel.cs within the ViewModels folder and then copy and paste the following code. This view model supports creating and updating employee records. It contains employee properties with validation and also includes lists for departments, designations, and employee types to populate dropdown menus.
using EmployeePortal.Models;
using System.ComponentModel.DataAnnotations;
namespace EmployeePortal.ViewModels
public class EmployeeCreateUpdateViewModel
public int? Id { get; set; }
[Display(Name = "Full Name")]
[Required(ErrorMessage = "Full Name is required")]
public string FullName { get; set; } = null!;
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; } = null!;
[Display(Name = "Department")]
[Required(ErrorMessage = "Department is required")]
public int DepartmentId { get; set; }
[Display(Name = "Designation")]
[Required(ErrorMessage = "Designation is required")]
public int DesignationId { get; set; }
[Display(Name = "Hire Date")]
[Required(ErrorMessage = "Hire Date is required")]
[DataType(DataType.Date)]
[CustomValidation(typeof(EmployeeCreateUpdateViewModel), nameof(ValidateHireDate))]
public DateTime HireDate { get; set; } = DateTime.Today;
[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "Date of Birth is required")]
[DataType(DataType.Date)]
[CustomValidation(typeof(EmployeeCreateUpdateViewModel), nameof(ValidateDateOfBirth))]
public DateTime DateOfBirth { get; set; } = DateTime.Today.AddYears(-60);
[Display(Name = "Employee Type")]
[Required(ErrorMessage = "Employee Type is required")]
public int EmployeeTypeId { get; set; }
[Required(ErrorMessage = "Gender is required")]
public string Gender { get; set; } = null!;
[Required(ErrorMessage = "Salary is required")]
[Range(0, double.MaxValue)]
public decimal Salary { get; set; }
public List<Department>? Departments { get; set; }
public List<Designation>? Designations { get; set; }
public List<EmployeeType>? EmployeeTypes { get; set; }
public static ValidationResult? ValidateHireDate(DateTime? hireDate, ValidationContext context)
return new ValidationResult("Hire Date is required.");
if (hireDate.Value.Date > DateTime.Today)
return new ValidationResult("Hire Date cannot be in the future.");
return ValidationResult.Success;
public static ValidationResult? ValidateDateOfBirth(DateTime? dob, ValidationContext context)
return new ValidationResult("Date of Birth is required.");
var minDob = DateTime.Today.AddYears(-60); // Max age 60 years (adjust as needed)
var maxDob = DateTime.Today.AddYears(-18); // Min working age 18 years
if (dob.Value.Date < minDob || dob.Value.Date > maxDob)
return new ValidationResult($"Date of Birth must be between {minDob:yyyy-MM-dd} and {maxDob:yyyy-MM-dd}.");
return ValidationResult.Success;
using EmployeePortal.Models;
using System.ComponentModel.DataAnnotations;
namespace EmployeePortal.ViewModels
{
public class EmployeeCreateUpdateViewModel
{
public int? Id { get; set; }
[Display(Name = "Full Name")]
[Required(ErrorMessage = "Full Name is required")]
[StringLength(100)]
public string FullName { get; set; } = null!;
[Required(ErrorMessage = "Email is required")]
[EmailAddress]
public string Email { get; set; } = null!;
[Display(Name = "Department")]
[Required(ErrorMessage = "Department is required")]
public int DepartmentId { get; set; }
[Display(Name = "Designation")]
[Required(ErrorMessage = "Designation is required")]
public int DesignationId { get; set; }
[Display(Name = "Hire Date")]
[Required(ErrorMessage = "Hire Date is required")]
[DataType(DataType.Date)]
[CustomValidation(typeof(EmployeeCreateUpdateViewModel), nameof(ValidateHireDate))]
public DateTime HireDate { get; set; } = DateTime.Today;
[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "Date of Birth is required")]
[DataType(DataType.Date)]
[CustomValidation(typeof(EmployeeCreateUpdateViewModel), nameof(ValidateDateOfBirth))]
public DateTime DateOfBirth { get; set; } = DateTime.Today.AddYears(-60);
[Display(Name = "Employee Type")]
[Required(ErrorMessage = "Employee Type is required")]
public int EmployeeTypeId { get; set; }
[Required(ErrorMessage = "Gender is required")]
public string Gender { get; set; } = null!;
[Required(ErrorMessage = "Salary is required")]
[Range(0, double.MaxValue)]
public decimal Salary { get; set; }
// For dropdown lists
public List<Department>? Departments { get; set; }
public List<Designation>? Designations { get; set; }
public List<EmployeeType>? EmployeeTypes { get; set; }
// Validation methods:
public static ValidationResult? ValidateHireDate(DateTime? hireDate, ValidationContext context)
{
if (!hireDate.HasValue)
return new ValidationResult("Hire Date is required.");
if (hireDate.Value.Date > DateTime.Today)
return new ValidationResult("Hire Date cannot be in the future.");
return ValidationResult.Success;
}
public static ValidationResult? ValidateDateOfBirth(DateTime? dob, ValidationContext context)
{
if (!dob.HasValue)
return new ValidationResult("Date of Birth is required.");
var minDob = DateTime.Today.AddYears(-60); // Max age 60 years (adjust as needed)
var maxDob = DateTime.Today.AddYears(-18); // Min working age 18 years
if (dob.Value.Date < minDob || dob.Value.Date > maxDob)
return new ValidationResult($"Date of Birth must be between {minDob:yyyy-MM-dd} and {maxDob:yyyy-MM-dd}.");
return ValidationResult.Success;
}
}
}
using EmployeePortal.Models;
using System.ComponentModel.DataAnnotations;
namespace EmployeePortal.ViewModels
{
public class EmployeeCreateUpdateViewModel
{
public int? Id { get; set; }
[Display(Name = "Full Name")]
[Required(ErrorMessage = "Full Name is required")]
[StringLength(100)]
public string FullName { get; set; } = null!;
[Required(ErrorMessage = "Email is required")]
[EmailAddress]
public string Email { get; set; } = null!;
[Display(Name = "Department")]
[Required(ErrorMessage = "Department is required")]
public int DepartmentId { get; set; }
[Display(Name = "Designation")]
[Required(ErrorMessage = "Designation is required")]
public int DesignationId { get; set; }
[Display(Name = "Hire Date")]
[Required(ErrorMessage = "Hire Date is required")]
[DataType(DataType.Date)]
[CustomValidation(typeof(EmployeeCreateUpdateViewModel), nameof(ValidateHireDate))]
public DateTime HireDate { get; set; } = DateTime.Today;
[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "Date of Birth is required")]
[DataType(DataType.Date)]
[CustomValidation(typeof(EmployeeCreateUpdateViewModel), nameof(ValidateDateOfBirth))]
public DateTime DateOfBirth { get; set; } = DateTime.Today.AddYears(-60);
[Display(Name = "Employee Type")]
[Required(ErrorMessage = "Employee Type is required")]
public int EmployeeTypeId { get; set; }
[Required(ErrorMessage = "Gender is required")]
public string Gender { get; set; } = null!;
[Required(ErrorMessage = "Salary is required")]
[Range(0, double.MaxValue)]
public decimal Salary { get; set; }
// For dropdown lists
public List<Department>? Departments { get; set; }
public List<Designation>? Designations { get; set; }
public List<EmployeeType>? EmployeeTypes { get; set; }
// Validation methods:
public static ValidationResult? ValidateHireDate(DateTime? hireDate, ValidationContext context)
{
if (!hireDate.HasValue)
return new ValidationResult("Hire Date is required.");
if (hireDate.Value.Date > DateTime.Today)
return new ValidationResult("Hire Date cannot be in the future.");
return ValidationResult.Success;
}
public static ValidationResult? ValidateDateOfBirth(DateTime? dob, ValidationContext context)
{
if (!dob.HasValue)
return new ValidationResult("Date of Birth is required.");
var minDob = DateTime.Today.AddYears(-60); // Max age 60 years (adjust as needed)
var maxDob = DateTime.Today.AddYears(-18); // Min working age 18 years
if (dob.Value.Date < minDob || dob.Value.Date > maxDob)
return new ValidationResult($"Date of Birth must be between {minDob:yyyy-MM-dd} and {maxDob:yyyy-MM-dd}.");
return ValidationResult.Success;
}
}
}
Create ApplicationDbContext Class
Create a new folder named ‘Data’ in the project root directory and add a class named ApplicationDbContext.cs to this folder. Then, copy and paste the following code. This class manages the database context using Entity Framework Core. It defines the tables for employees, departments, designations, and employee types and seeds initial data into the database.
using EmployeePortal.Models;
using Microsoft.EntityFrameworkCore;
namespace EmployeePortal.Data
public class ApplicationDbContext : DbContext
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Designation> Designations { get; set; }
public DbSet<EmployeeType> EmployeeTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
base.OnModelCreating(modelBuilder);
// Prevent cascade delete on Designation FK
modelBuilder.Entity<Employee>()
.HasOne(e => e.Designation)
.HasForeignKey(e => e.DesignationId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<EmployeeType>().HasData(
new EmployeeType { Id = 1, Name = "Permanent" },
new EmployeeType { Id = 2, Name = "Temporary" },
new EmployeeType { Id = 3, Name = "Contract" },
new EmployeeType { Id = 4, Name = "Intern" }
modelBuilder.Entity<Department>().HasData(
new Department { Id = 1, Name = "IT" },
new Department { Id = 2, Name = "HR" },
new Department { Id = 3, Name = "Sales" },
new Department { Id = 4, Name = "Admin" }
// Seed Designations with DepartmentId
modelBuilder.Entity<Designation>().HasData(
new Designation { Id = 1, Name = "Software Developer", DepartmentId = 1 },
new Designation { Id = 2, Name = "System Administrator", DepartmentId = 1 },
new Designation { Id = 3, Name = "Network Engineer", DepartmentId = 1 },
new Designation { Id = 4, Name = "HR Specialist", DepartmentId = 2 },
new Designation { Id = 5, Name = "HR Manager", DepartmentId = 2 },
new Designation { Id = 6, Name = "Talent Acquisition Coordinator", DepartmentId = 2 },
new Designation { Id = 7, Name = "Sales Executive", DepartmentId = 3 },
new Designation { Id = 8, Name = "Sales Manager", DepartmentId = 3 },
new Designation { Id = 9, Name = "Account Executive", DepartmentId = 3 },
new Designation { Id = 10, Name = "Office Manager", DepartmentId = 4 },
new Designation { Id = 11, Name = "Executive Assistant", DepartmentId = 4 },
new Designation { Id = 12, Name = "Receptionist", DepartmentId = 4 }
modelBuilder.Entity<Employee>().HasData(
new Employee { Id = 1, FullName = "John Doe", Email = "john@example.com", DepartmentId = 1, DesignationId = 1, HireDate = new DateTime(2020, 1, 15), DateOfBirth = new DateTime(1990, 3, 12), EmployeeTypeId = 1, Gender = "Male", Salary = 60000m },
new Employee { Id = 2, FullName = "Jane Smith", Email = "jane@example.com", DepartmentId = 2, DesignationId = 5, HireDate = new DateTime(2018, 5, 20), DateOfBirth = new DateTime(1985, 8, 22), EmployeeTypeId = 1, Gender = "Female", Salary = 80000m },
new Employee { Id = 3, FullName = "Sam Wilson", Email = "sam@example.com", DepartmentId = 3, DesignationId = 7, HireDate = new DateTime(2021, 3, 10), DateOfBirth = new DateTime(1992, 6, 30), EmployeeTypeId = 3, Gender = "Male", Salary = 50000m },
new Employee { Id = 4, FullName = "Anna Taylor", Email = "anna@example.com", DepartmentId = 4, DesignationId = 11, HireDate = new DateTime(2022, 7, 5), DateOfBirth = new DateTime(1995, 11, 15), EmployeeTypeId = 2, Gender = "Female", Salary = 40000m },
new Employee { Id = 5, FullName = "Tom Brown", Email = "tom@example.com", DepartmentId = 1, DesignationId = 3, HireDate = new DateTime(2019, 4, 18), DateOfBirth = new DateTime(1989, 2, 25), EmployeeTypeId = 1, Gender = "Male", Salary = 70000m },
new Employee { Id = 6, FullName = "Emma Davis", Email = "emma@example.com", DepartmentId = 2, DesignationId = 4, HireDate = new DateTime(2017, 10, 12), DateOfBirth = new DateTime(1987, 9, 10), EmployeeTypeId = 1, Gender = "Female", Salary = 75000m },
new Employee { Id = 7, FullName = "Luke Miller", Email = "luke@example.com", DepartmentId = 3, DesignationId = 8, HireDate = new DateTime(2020, 2, 20), DateOfBirth = new DateTime(1990, 1, 5), EmployeeTypeId = 3, Gender = "Male", Salary = 85000m },
new Employee { Id = 8, FullName = "Olivia Johnson", Email = "olivia@example.com", DepartmentId = 4, DesignationId = 10, HireDate = new DateTime(2021, 6, 8), DateOfBirth = new DateTime(1993, 4, 18), EmployeeTypeId = 1, Gender = "Female", Salary = 65000m },
new Employee { Id = 9, FullName = "Mia Moore", Email = "mia@example.com", DepartmentId = 1, DesignationId = 2, HireDate = new DateTime(2022, 8, 15), DateOfBirth = new DateTime(1997, 12, 20), EmployeeTypeId = 4, Gender = "Female", Salary = 30000m },
new Employee { Id = 10, FullName = "Chris Evans", Email = "chris@example.com", DepartmentId = 2, DesignationId = 6, HireDate = new DateTime(2018, 11, 25), DateOfBirth = new DateTime(1986, 7, 12), EmployeeTypeId = 2, Gender = "Other", Salary = 55000m },
new Employee { Id = 11, FullName = "Sophia White", Email = "sophia@example.com", DepartmentId = 3, DesignationId = 7, HireDate = new DateTime(2019, 9, 10), DateOfBirth = new DateTime(1994, 5, 6), EmployeeTypeId = 1, Gender = "Female", Salary = 52000m },
new Employee { Id = 12, FullName = "Liam Green", Email = "liam@example.com", DepartmentId = 4, DesignationId = 12, HireDate = new DateTime(2020, 10, 3), DateOfBirth = new DateTime(1996, 8, 21), EmployeeTypeId = 2, Gender = "Male", Salary = 38000m },
new Employee { Id = 13, FullName = "Noah Black", Email = "noah@example.com", DepartmentId = 1, DesignationId = 2, HireDate = new DateTime(2018, 12, 1), DateOfBirth = new DateTime(1991, 9, 18), EmployeeTypeId = 1, Gender = "Male", Salary = 65000m },
new Employee { Id = 14, FullName = "Isabella Blue", Email = "isabella@example.com", DepartmentId = 2, DesignationId = 4, HireDate = new DateTime(2017, 11, 30), DateOfBirth = new DateTime(1988, 4, 2), EmployeeTypeId = 1, Gender = "Female", Salary = 76000m },
new Employee { Id = 15, FullName = "James Brown", Email = "james@example.com", DepartmentId = 3, DesignationId = 9, HireDate = new DateTime(2021, 7, 21), DateOfBirth = new DateTime(1993, 3, 17), EmployeeTypeId = 3, Gender = "Male", Salary = 62000m }
using EmployeePortal.Models;
using Microsoft.EntityFrameworkCore;
namespace EmployeePortal.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Designation> Designations { get; set; }
public DbSet<EmployeeType> EmployeeTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Prevent cascade delete on Designation FK
modelBuilder.Entity<Employee>()
.HasOne(e => e.Designation)
.WithMany()
.HasForeignKey(e => e.DesignationId)
.OnDelete(DeleteBehavior.Restrict);
// Seed EmployeeTypes
modelBuilder.Entity<EmployeeType>().HasData(
new EmployeeType { Id = 1, Name = "Permanent" },
new EmployeeType { Id = 2, Name = "Temporary" },
new EmployeeType { Id = 3, Name = "Contract" },
new EmployeeType { Id = 4, Name = "Intern" }
);
// Seed Departments
modelBuilder.Entity<Department>().HasData(
new Department { Id = 1, Name = "IT" },
new Department { Id = 2, Name = "HR" },
new Department { Id = 3, Name = "Sales" },
new Department { Id = 4, Name = "Admin" }
);
// Seed Designations with DepartmentId
modelBuilder.Entity<Designation>().HasData(
new Designation { Id = 1, Name = "Software Developer", DepartmentId = 1 },
new Designation { Id = 2, Name = "System Administrator", DepartmentId = 1 },
new Designation { Id = 3, Name = "Network Engineer", DepartmentId = 1 },
new Designation { Id = 4, Name = "HR Specialist", DepartmentId = 2 },
new Designation { Id = 5, Name = "HR Manager", DepartmentId = 2 },
new Designation { Id = 6, Name = "Talent Acquisition Coordinator", DepartmentId = 2 },
new Designation { Id = 7, Name = "Sales Executive", DepartmentId = 3 },
new Designation { Id = 8, Name = "Sales Manager", DepartmentId = 3 },
new Designation { Id = 9, Name = "Account Executive", DepartmentId = 3 },
new Designation { Id = 10, Name = "Office Manager", DepartmentId = 4 },
new Designation { Id = 11, Name = "Executive Assistant", DepartmentId = 4 },
new Designation { Id = 12, Name = "Receptionist", DepartmentId = 4 }
);
// Seed initial data
modelBuilder.Entity<Employee>().HasData(
new Employee { Id = 1, FullName = "John Doe", Email = "john@example.com", DepartmentId = 1, DesignationId = 1, HireDate = new DateTime(2020, 1, 15), DateOfBirth = new DateTime(1990, 3, 12), EmployeeTypeId = 1, Gender = "Male", Salary = 60000m },
new Employee { Id = 2, FullName = "Jane Smith", Email = "jane@example.com", DepartmentId = 2, DesignationId = 5, HireDate = new DateTime(2018, 5, 20), DateOfBirth = new DateTime(1985, 8, 22), EmployeeTypeId = 1, Gender = "Female", Salary = 80000m },
new Employee { Id = 3, FullName = "Sam Wilson", Email = "sam@example.com", DepartmentId = 3, DesignationId = 7, HireDate = new DateTime(2021, 3, 10), DateOfBirth = new DateTime(1992, 6, 30), EmployeeTypeId = 3, Gender = "Male", Salary = 50000m },
new Employee { Id = 4, FullName = "Anna Taylor", Email = "anna@example.com", DepartmentId = 4, DesignationId = 11, HireDate = new DateTime(2022, 7, 5), DateOfBirth = new DateTime(1995, 11, 15), EmployeeTypeId = 2, Gender = "Female", Salary = 40000m },
new Employee { Id = 5, FullName = "Tom Brown", Email = "tom@example.com", DepartmentId = 1, DesignationId = 3, HireDate = new DateTime(2019, 4, 18), DateOfBirth = new DateTime(1989, 2, 25), EmployeeTypeId = 1, Gender = "Male", Salary = 70000m },
new Employee { Id = 6, FullName = "Emma Davis", Email = "emma@example.com", DepartmentId = 2, DesignationId = 4, HireDate = new DateTime(2017, 10, 12), DateOfBirth = new DateTime(1987, 9, 10), EmployeeTypeId = 1, Gender = "Female", Salary = 75000m },
new Employee { Id = 7, FullName = "Luke Miller", Email = "luke@example.com", DepartmentId = 3, DesignationId = 8, HireDate = new DateTime(2020, 2, 20), DateOfBirth = new DateTime(1990, 1, 5), EmployeeTypeId = 3, Gender = "Male", Salary = 85000m },
new Employee { Id = 8, FullName = "Olivia Johnson", Email = "olivia@example.com", DepartmentId = 4, DesignationId = 10, HireDate = new DateTime(2021, 6, 8), DateOfBirth = new DateTime(1993, 4, 18), EmployeeTypeId = 1, Gender = "Female", Salary = 65000m },
new Employee { Id = 9, FullName = "Mia Moore", Email = "mia@example.com", DepartmentId = 1, DesignationId = 2, HireDate = new DateTime(2022, 8, 15), DateOfBirth = new DateTime(1997, 12, 20), EmployeeTypeId = 4, Gender = "Female", Salary = 30000m },
new Employee { Id = 10, FullName = "Chris Evans", Email = "chris@example.com", DepartmentId = 2, DesignationId = 6, HireDate = new DateTime(2018, 11, 25), DateOfBirth = new DateTime(1986, 7, 12), EmployeeTypeId = 2, Gender = "Other", Salary = 55000m },
new Employee { Id = 11, FullName = "Sophia White", Email = "sophia@example.com", DepartmentId = 3, DesignationId = 7, HireDate = new DateTime(2019, 9, 10), DateOfBirth = new DateTime(1994, 5, 6), EmployeeTypeId = 1, Gender = "Female", Salary = 52000m },
new Employee { Id = 12, FullName = "Liam Green", Email = "liam@example.com", DepartmentId = 4, DesignationId = 12, HireDate = new DateTime(2020, 10, 3), DateOfBirth = new DateTime(1996, 8, 21), EmployeeTypeId = 2, Gender = "Male", Salary = 38000m },
new Employee { Id = 13, FullName = "Noah Black", Email = "noah@example.com", DepartmentId = 1, DesignationId = 2, HireDate = new DateTime(2018, 12, 1), DateOfBirth = new DateTime(1991, 9, 18), EmployeeTypeId = 1, Gender = "Male", Salary = 65000m },
new Employee { Id = 14, FullName = "Isabella Blue", Email = "isabella@example.com", DepartmentId = 2, DesignationId = 4, HireDate = new DateTime(2017, 11, 30), DateOfBirth = new DateTime(1988, 4, 2), EmployeeTypeId = 1, Gender = "Female", Salary = 76000m },
new Employee { Id = 15, FullName = "James Brown", Email = "james@example.com", DepartmentId = 3, DesignationId = 9, HireDate = new DateTime(2021, 7, 21), DateOfBirth = new DateTime(1993, 3, 17), EmployeeTypeId = 3, Gender = "Male", Salary = 62000m }
);
}
}
}
using EmployeePortal.Models;
using Microsoft.EntityFrameworkCore;
namespace EmployeePortal.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Designation> Designations { get; set; }
public DbSet<EmployeeType> EmployeeTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Prevent cascade delete on Designation FK
modelBuilder.Entity<Employee>()
.HasOne(e => e.Designation)
.WithMany()
.HasForeignKey(e => e.DesignationId)
.OnDelete(DeleteBehavior.Restrict);
// Seed EmployeeTypes
modelBuilder.Entity<EmployeeType>().HasData(
new EmployeeType { Id = 1, Name = "Permanent" },
new EmployeeType { Id = 2, Name = "Temporary" },
new EmployeeType { Id = 3, Name = "Contract" },
new EmployeeType { Id = 4, Name = "Intern" }
);
// Seed Departments
modelBuilder.Entity<Department>().HasData(
new Department { Id = 1, Name = "IT" },
new Department { Id = 2, Name = "HR" },
new Department { Id = 3, Name = "Sales" },
new Department { Id = 4, Name = "Admin" }
);
// Seed Designations with DepartmentId
modelBuilder.Entity<Designation>().HasData(
new Designation { Id = 1, Name = "Software Developer", DepartmentId = 1 },
new Designation { Id = 2, Name = "System Administrator", DepartmentId = 1 },
new Designation { Id = 3, Name = "Network Engineer", DepartmentId = 1 },
new Designation { Id = 4, Name = "HR Specialist", DepartmentId = 2 },
new Designation { Id = 5, Name = "HR Manager", DepartmentId = 2 },
new Designation { Id = 6, Name = "Talent Acquisition Coordinator", DepartmentId = 2 },
new Designation { Id = 7, Name = "Sales Executive", DepartmentId = 3 },
new Designation { Id = 8, Name = "Sales Manager", DepartmentId = 3 },
new Designation { Id = 9, Name = "Account Executive", DepartmentId = 3 },
new Designation { Id = 10, Name = "Office Manager", DepartmentId = 4 },
new Designation { Id = 11, Name = "Executive Assistant", DepartmentId = 4 },
new Designation { Id = 12, Name = "Receptionist", DepartmentId = 4 }
);
// Seed initial data
modelBuilder.Entity<Employee>().HasData(
new Employee { Id = 1, FullName = "John Doe", Email = "john@example.com", DepartmentId = 1, DesignationId = 1, HireDate = new DateTime(2020, 1, 15), DateOfBirth = new DateTime(1990, 3, 12), EmployeeTypeId = 1, Gender = "Male", Salary = 60000m },
new Employee { Id = 2, FullName = "Jane Smith", Email = "jane@example.com", DepartmentId = 2, DesignationId = 5, HireDate = new DateTime(2018, 5, 20), DateOfBirth = new DateTime(1985, 8, 22), EmployeeTypeId = 1, Gender = "Female", Salary = 80000m },
new Employee { Id = 3, FullName = "Sam Wilson", Email = "sam@example.com", DepartmentId = 3, DesignationId = 7, HireDate = new DateTime(2021, 3, 10), DateOfBirth = new DateTime(1992, 6, 30), EmployeeTypeId = 3, Gender = "Male", Salary = 50000m },
new Employee { Id = 4, FullName = "Anna Taylor", Email = "anna@example.com", DepartmentId = 4, DesignationId = 11, HireDate = new DateTime(2022, 7, 5), DateOfBirth = new DateTime(1995, 11, 15), EmployeeTypeId = 2, Gender = "Female", Salary = 40000m },
new Employee { Id = 5, FullName = "Tom Brown", Email = "tom@example.com", DepartmentId = 1, DesignationId = 3, HireDate = new DateTime(2019, 4, 18), DateOfBirth = new DateTime(1989, 2, 25), EmployeeTypeId = 1, Gender = "Male", Salary = 70000m },
new Employee { Id = 6, FullName = "Emma Davis", Email = "emma@example.com", DepartmentId = 2, DesignationId = 4, HireDate = new DateTime(2017, 10, 12), DateOfBirth = new DateTime(1987, 9, 10), EmployeeTypeId = 1, Gender = "Female", Salary = 75000m },
new Employee { Id = 7, FullName = "Luke Miller", Email = "luke@example.com", DepartmentId = 3, DesignationId = 8, HireDate = new DateTime(2020, 2, 20), DateOfBirth = new DateTime(1990, 1, 5), EmployeeTypeId = 3, Gender = "Male", Salary = 85000m },
new Employee { Id = 8, FullName = "Olivia Johnson", Email = "olivia@example.com", DepartmentId = 4, DesignationId = 10, HireDate = new DateTime(2021, 6, 8), DateOfBirth = new DateTime(1993, 4, 18), EmployeeTypeId = 1, Gender = "Female", Salary = 65000m },
new Employee { Id = 9, FullName = "Mia Moore", Email = "mia@example.com", DepartmentId = 1, DesignationId = 2, HireDate = new DateTime(2022, 8, 15), DateOfBirth = new DateTime(1997, 12, 20), EmployeeTypeId = 4, Gender = "Female", Salary = 30000m },
new Employee { Id = 10, FullName = "Chris Evans", Email = "chris@example.com", DepartmentId = 2, DesignationId = 6, HireDate = new DateTime(2018, 11, 25), DateOfBirth = new DateTime(1986, 7, 12), EmployeeTypeId = 2, Gender = "Other", Salary = 55000m },
new Employee { Id = 11, FullName = "Sophia White", Email = "sophia@example.com", DepartmentId = 3, DesignationId = 7, HireDate = new DateTime(2019, 9, 10), DateOfBirth = new DateTime(1994, 5, 6), EmployeeTypeId = 1, Gender = "Female", Salary = 52000m },
new Employee { Id = 12, FullName = "Liam Green", Email = "liam@example.com", DepartmentId = 4, DesignationId = 12, HireDate = new DateTime(2020, 10, 3), DateOfBirth = new DateTime(1996, 8, 21), EmployeeTypeId = 2, Gender = "Male", Salary = 38000m },
new Employee { Id = 13, FullName = "Noah Black", Email = "noah@example.com", DepartmentId = 1, DesignationId = 2, HireDate = new DateTime(2018, 12, 1), DateOfBirth = new DateTime(1991, 9, 18), EmployeeTypeId = 1, Gender = "Male", Salary = 65000m },
new Employee { Id = 14, FullName = "Isabella Blue", Email = "isabella@example.com", DepartmentId = 2, DesignationId = 4, HireDate = new DateTime(2017, 11, 30), DateOfBirth = new DateTime(1988, 4, 2), EmployeeTypeId = 1, Gender = "Female", Salary = 76000m },
new Employee { Id = 15, FullName = "James Brown", Email = "james@example.com", DepartmentId = 3, DesignationId = 9, HireDate = new DateTime(2021, 7, 21), DateOfBirth = new DateTime(1993, 3, 17), EmployeeTypeId = 3, Gender = "Male", Salary = 62000m }
);
}
}
}
Employee Service:
Next, create a class file named EmployeeService.cs within the Services folder (please create this folder at the project root directory) and copy and paste the following code. This service class handles all business logic and database operations for employees. It supports creating, reading, updating, deleting employees, and fetching master data, such as departments and designations.
using EmployeePortal.Data;
using EmployeePortal.Models;
using Microsoft.EntityFrameworkCore;
namespace EmployeePortal.Services
public class EmployeeService
private readonly ApplicationDbContext _context;
public EmployeeService(ApplicationDbContext context)
public async Task<(List<Employee> Employees, int TotalCount)> GetEmployees(
var query = _context.Employees
.Include(e => e.Department)
.Include(e => e.Designation)
.Include(e => e.EmployeeType)
if (!string.IsNullOrWhiteSpace(searchTerm))
query = query.Where(e => e.FullName.Contains(searchTerm));
if (departmentId.HasValue && departmentId.Value > 0)
query = query.Where(e => e.DepartmentId == departmentId.Value);
if (employeeTypeId.HasValue && employeeTypeId.Value > 0)
query = query.Where(e => e.EmployeeTypeId == employeeTypeId.Value);
var totalCount = await query.CountAsync();
var employees = await query
.Skip((pageNumber - 1) * pageSize)
return (employees, totalCount);
public async Task<Employee?> GetEmployeeByIdAsync(int id)
return await _context.Employees
.Include(e => e.Department)
.Include(e => e.Designation)
.Include(e => e.EmployeeType)
.FirstOrDefaultAsync(e => e.Id == id);
public async Task CreateEmployeeAsync(Employee employee)
_context.Employees.Add(employee);
await _context.SaveChangesAsync();
public async Task UpdateEmployeeAsync(Employee employee)
_context.Entry(employee).State = EntityState.Modified;
await _context.SaveChangesAsync();
public async Task DeleteEmployeeAsync(int id)
var employee = await GetEmployeeByIdAsync(id);
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
// Master tables retrieval
public async Task<List<Department>> GetDepartmentsAsync()
return await _context.Departments.AsNoTracking().ToListAsync();
public async Task<List<EmployeeType>> GetEmployeeTypesAsync()
return await _context.EmployeeTypes.AsNoTracking().ToListAsync();
public async Task<List<Designation>> GetDesignationsByDepartmentAsync(int departmentId)
return await _context.Designations
.Where(d => d.DepartmentId == departmentId)
using EmployeePortal.Data;
using EmployeePortal.Models;
using Microsoft.EntityFrameworkCore;
namespace EmployeePortal.Services
{
public class EmployeeService
{
private readonly ApplicationDbContext _context;
public EmployeeService(ApplicationDbContext context)
{
_context = context;
}
public async Task<(List<Employee> Employees, int TotalCount)> GetEmployees(
string? searchTerm,
int? departmentId,
int? employeeTypeId,
int pageNumber,
int pageSize)
{
var query = _context.Employees
.Include(e => e.Department)
.Include(e => e.Designation)
.Include(e => e.EmployeeType)
.AsQueryable();
if (!string.IsNullOrWhiteSpace(searchTerm))
{
query = query.Where(e => e.FullName.Contains(searchTerm));
}
if (departmentId.HasValue && departmentId.Value > 0)
{
query = query.Where(e => e.DepartmentId == departmentId.Value);
}
if (employeeTypeId.HasValue && employeeTypeId.Value > 0)
{
query = query.Where(e => e.EmployeeTypeId == employeeTypeId.Value);
}
var totalCount = await query.CountAsync();
var employees = await query
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.AsNoTracking()
.ToListAsync();
return (employees, totalCount);
}
public async Task<Employee?> GetEmployeeByIdAsync(int id)
{
return await _context.Employees
.Include(e => e.Department)
.Include(e => e.Designation)
.Include(e => e.EmployeeType)
.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == id);
}
public async Task CreateEmployeeAsync(Employee employee)
{
_context.Employees.Add(employee);
await _context.SaveChangesAsync();
}
public async Task UpdateEmployeeAsync(Employee employee)
{
_context.Entry(employee).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
public async Task DeleteEmployeeAsync(int id)
{
var employee = await GetEmployeeByIdAsync(id);
if (employee != null)
{
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
}
}
// Master tables retrieval
public async Task<List<Department>> GetDepartmentsAsync()
{
return await _context.Departments.AsNoTracking().ToListAsync();
}
public async Task<List<EmployeeType>> GetEmployeeTypesAsync()
{
return await _context.EmployeeTypes.AsNoTracking().ToListAsync();
}
public async Task<List<Designation>> GetDesignationsByDepartmentAsync(int departmentId)
{
return await _context.Designations
.Where(d => d.DepartmentId == departmentId)
.AsNoTracking()
.ToListAsync();
}
}
}
using EmployeePortal.Data;
using EmployeePortal.Models;
using Microsoft.EntityFrameworkCore;
namespace EmployeePortal.Services
{
public class EmployeeService
{
private readonly ApplicationDbContext _context;
public EmployeeService(ApplicationDbContext context)
{
_context = context;
}
public async Task<(List<Employee> Employees, int TotalCount)> GetEmployees(
string? searchTerm,
int? departmentId,
int? employeeTypeId,
int pageNumber,
int pageSize)
{
var query = _context.Employees
.Include(e => e.Department)
.Include(e => e.Designation)
.Include(e => e.EmployeeType)
.AsQueryable();
if (!string.IsNullOrWhiteSpace(searchTerm))
{
query = query.Where(e => e.FullName.Contains(searchTerm));
}
if (departmentId.HasValue && departmentId.Value > 0)
{
query = query.Where(e => e.DepartmentId == departmentId.Value);
}
if (employeeTypeId.HasValue && employeeTypeId.Value > 0)
{
query = query.Where(e => e.EmployeeTypeId == employeeTypeId.Value);
}
var totalCount = await query.CountAsync();
var employees = await query
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.AsNoTracking()
.ToListAsync();
return (employees, totalCount);
}
public async Task<Employee?> GetEmployeeByIdAsync(int id)
{
return await _context.Employees
.Include(e => e.Department)
.Include(e => e.Designation)
.Include(e => e.EmployeeType)
.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == id);
}
public async Task CreateEmployeeAsync(Employee employee)
{
_context.Employees.Add(employee);
await _context.SaveChangesAsync();
}
public async Task UpdateEmployeeAsync(Employee employee)
{
_context.Entry(employee).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
public async Task DeleteEmployeeAsync(int id)
{
var employee = await GetEmployeeByIdAsync(id);
if (employee != null)
{
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
}
}
// Master tables retrieval
public async Task<List<Department>> GetDepartmentsAsync()
{
return await _context.Departments.AsNoTracking().ToListAsync();
}
public async Task<List<EmployeeType>> GetEmployeeTypesAsync()
{
return await _context.EmployeeTypes.AsNoTracking().ToListAsync();
}
public async Task<List<Designation>> GetDesignationsByDepartmentAsync(int departmentId)
{
return await _context.Designations
.Where(d => d.DepartmentId == departmentId)
.AsNoTracking()
.ToListAsync();
}
}
}
Add Connection String to appsettings.json
Please modify the appsettings.json file as follows. This configuration file stores application settings, including logging levels and database connection strings. The connection string here tells the app how to connect to the SQL Server database where employee data is stored and managed.
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"ECommerceDBConnection": "Server=LAPTOP-6P5NK25R\\SQLSERVER2022DEV;Database=EmployeePortalDB;Trusted_Connection=True;TrustServerCertificate=True;"
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ECommerceDBConnection": "Server=LAPTOP-6P5NK25R\\SQLSERVER2022DEV;Database=EmployeePortalDB;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ECommerceDBConnection": "Server=LAPTOP-6P5NK25R\\SQLSERVER2022DEV;Database=EmployeePortalDB;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
Employee Controller:
Next, create an Empty MVC Controller named EmployeeController within the Controllers folder and then copy and paste the following code. This controller manages HTTP requests for employee-related actions. It handles showing employee lists, creating, updating, and deleting employees, and provides JSON data for dynamic dropdowns.
using EmployeePortal.Models;
using EmployeePortal.Services;
using EmployeePortal.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace EmployeePortal.Controllers
public class EmployeeController : Controller
private readonly EmployeeService _employeeService;
public EmployeeController(EmployeeService employeeService)
_employeeService = employeeService;
public async Task<IActionResult> List(
int? SelectedDepartmentId,
int? SelectedEmployeeTypeId,
var (employees, totalCount) = await _employeeService.GetEmployees(searchTerm, SelectedDepartmentId, SelectedEmployeeTypeId, pageNumber, pageSize);
var viewModel = new EmployeeListViewModel
TotalPages = (int)Math.Ceiling((double)totalCount / pageSize),
SelectedDepartmentId = SelectedDepartmentId,
SelectedEmployeeTypeId = SelectedEmployeeTypeId,
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync()
public async Task<IActionResult> Create()
var vm = new EmployeeCreateUpdateViewModel
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync(),
Designations = new List<Designation>()
public async Task<IActionResult> Create(EmployeeCreateUpdateViewModel vm)
var employee = new Employee
DepartmentId = vm.DepartmentId,
DesignationId = vm.DesignationId,
DateOfBirth = vm.DateOfBirth,
EmployeeTypeId = vm.EmployeeTypeId,
await _employeeService.CreateEmployeeAsync(employee);
return RedirectToAction("Success", new { id = employee.Id });
vm.Departments = await _employeeService.GetDepartmentsAsync();
vm.EmployeeTypes = await _employeeService.GetEmployeeTypesAsync();
vm.Designations = vm.DepartmentId != 0 ? await _employeeService.GetDesignationsByDepartmentAsync(vm.DepartmentId) : new List<Designation>();
public async Task<IActionResult> Update(int id)
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
var vm = new EmployeeCreateUpdateViewModel
FullName = employee.FullName,
DepartmentId = employee.DepartmentId,
DesignationId = employee.DesignationId,
HireDate = employee.HireDate,
DateOfBirth = employee.DateOfBirth,
EmployeeTypeId = employee.EmployeeTypeId,
Gender = employee.Gender,
Salary = employee.Salary,
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync(),
Designations = await _employeeService.GetDesignationsByDepartmentAsync(employee.DepartmentId)
public async Task<IActionResult> Update(EmployeeCreateUpdateViewModel vm)
var employee = new Employee
DepartmentId = vm.DepartmentId,
DesignationId = vm.DesignationId,
DateOfBirth = vm.DateOfBirth,
EmployeeTypeId = vm.EmployeeTypeId,
await _employeeService.UpdateEmployeeAsync(employee);
TempData["Message"] = $"Employee with ID {employee.Id} and Name {employee.FullName} has been updated.";
return RedirectToAction("List");
vm.Departments = await _employeeService.GetDepartmentsAsync();
vm.EmployeeTypes = await _employeeService.GetEmployeeTypesAsync();
vm.Designations = vm.DepartmentId != 0 ? await _employeeService.GetDesignationsByDepartmentAsync(vm.DepartmentId) : new List<Designation>();
public async Task<IActionResult> Delete(int id)
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
[HttpPost, ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(int id)
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
await _employeeService.DeleteEmployeeAsync(id);
TempData["Message"] = $"Employee with ID {id} and Name {employee.FullName} has been deleted.";
return RedirectToAction("List");
public async Task<JsonResult> GetDesignations(int departmentId)
var designations = await _employeeService.GetDesignationsByDepartmentAsync(departmentId);
var result = designations.Select(d => new { id = d.Id, name = d.Name }).ToList();
public async Task<IActionResult> Success(int id)
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
public async Task<IActionResult> Details(int id)
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
using EmployeePortal.Models;
using EmployeePortal.Services;
using EmployeePortal.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace EmployeePortal.Controllers
{
public class EmployeeController : Controller
{
private readonly EmployeeService _employeeService;
public EmployeeController(EmployeeService employeeService)
{
_employeeService = employeeService;
}
[HttpGet]
public async Task<IActionResult> List(
string? searchTerm,
int? SelectedDepartmentId,
int? SelectedEmployeeTypeId,
int pageNumber = 1,
int pageSize = 5)
{
var (employees, totalCount) = await _employeeService.GetEmployees(searchTerm, SelectedDepartmentId, SelectedEmployeeTypeId, pageNumber, pageSize);
var viewModel = new EmployeeListViewModel
{
Employees = employees,
PageNumber = pageNumber,
PageSize = pageSize,
Total = totalCount,
TotalPages = (int)Math.Ceiling((double)totalCount / pageSize),
SearchTerm = searchTerm,
SelectedDepartmentId = SelectedDepartmentId,
SelectedEmployeeTypeId = SelectedEmployeeTypeId,
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync()
};
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Create()
{
var vm = new EmployeeCreateUpdateViewModel
{
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync(),
Designations = new List<Designation>()
};
return View(vm);
}
[HttpPost]
public async Task<IActionResult> Create(EmployeeCreateUpdateViewModel vm)
{
if (ModelState.IsValid)
{
var employee = new Employee
{
FullName = vm.FullName,
Email = vm.Email,
DepartmentId = vm.DepartmentId,
DesignationId = vm.DesignationId,
HireDate = vm.HireDate,
DateOfBirth = vm.DateOfBirth,
EmployeeTypeId = vm.EmployeeTypeId,
Gender = vm.Gender,
Salary = vm.Salary
};
await _employeeService.CreateEmployeeAsync(employee);
return RedirectToAction("Success", new { id = employee.Id });
}
vm.Departments = await _employeeService.GetDepartmentsAsync();
vm.EmployeeTypes = await _employeeService.GetEmployeeTypesAsync();
vm.Designations = vm.DepartmentId != 0 ? await _employeeService.GetDesignationsByDepartmentAsync(vm.DepartmentId) : new List<Designation>();
return View(vm);
}
[HttpGet]
public async Task<IActionResult> Update(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
var vm = new EmployeeCreateUpdateViewModel
{
Id = employee.Id,
FullName = employee.FullName,
Email = employee.Email,
DepartmentId = employee.DepartmentId,
DesignationId = employee.DesignationId,
HireDate = employee.HireDate,
DateOfBirth = employee.DateOfBirth,
EmployeeTypeId = employee.EmployeeTypeId,
Gender = employee.Gender,
Salary = employee.Salary,
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync(),
Designations = await _employeeService.GetDesignationsByDepartmentAsync(employee.DepartmentId)
};
return View(vm);
}
[HttpPost]
public async Task<IActionResult> Update(EmployeeCreateUpdateViewModel vm)
{
if (ModelState.IsValid)
{
var employee = new Employee
{
Id = vm.Id!.Value,
FullName = vm.FullName,
Email = vm.Email,
DepartmentId = vm.DepartmentId,
DesignationId = vm.DesignationId,
HireDate = vm.HireDate,
DateOfBirth = vm.DateOfBirth,
EmployeeTypeId = vm.EmployeeTypeId,
Gender = vm.Gender,
Salary = vm.Salary
};
await _employeeService.UpdateEmployeeAsync(employee);
TempData["Message"] = $"Employee with ID {employee.Id} and Name {employee.FullName} has been updated.";
return RedirectToAction("List");
}
vm.Departments = await _employeeService.GetDepartmentsAsync();
vm.EmployeeTypes = await _employeeService.GetEmployeeTypesAsync();
vm.Designations = vm.DepartmentId != 0 ? await _employeeService.GetDesignationsByDepartmentAsync(vm.DepartmentId) : new List<Designation>();
return View(vm);
}
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
return View(employee);
}
[HttpPost, ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
await _employeeService.DeleteEmployeeAsync(id);
TempData["Message"] = $"Employee with ID {id} and Name {employee.FullName} has been deleted.";
return RedirectToAction("List");
}
[HttpGet]
public async Task<JsonResult> GetDesignations(int departmentId)
{
var designations = await _employeeService.GetDesignationsByDepartmentAsync(departmentId);
var result = designations.Select(d => new { id = d.Id, name = d.Name }).ToList();
return Json(result);
}
[HttpGet]
public async Task<IActionResult> Success(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
return View(employee);
}
[HttpGet]
public async Task<IActionResult> Details(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
return View(employee);
}
}
}
using EmployeePortal.Models;
using EmployeePortal.Services;
using EmployeePortal.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace EmployeePortal.Controllers
{
public class EmployeeController : Controller
{
private readonly EmployeeService _employeeService;
public EmployeeController(EmployeeService employeeService)
{
_employeeService = employeeService;
}
[HttpGet]
public async Task<IActionResult> List(
string? searchTerm,
int? SelectedDepartmentId,
int? SelectedEmployeeTypeId,
int pageNumber = 1,
int pageSize = 5)
{
var (employees, totalCount) = await _employeeService.GetEmployees(searchTerm, SelectedDepartmentId, SelectedEmployeeTypeId, pageNumber, pageSize);
var viewModel = new EmployeeListViewModel
{
Employees = employees,
PageNumber = pageNumber,
PageSize = pageSize,
Total = totalCount,
TotalPages = (int)Math.Ceiling((double)totalCount / pageSize),
SearchTerm = searchTerm,
SelectedDepartmentId = SelectedDepartmentId,
SelectedEmployeeTypeId = SelectedEmployeeTypeId,
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync()
};
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Create()
{
var vm = new EmployeeCreateUpdateViewModel
{
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync(),
Designations = new List<Designation>()
};
return View(vm);
}
[HttpPost]
public async Task<IActionResult> Create(EmployeeCreateUpdateViewModel vm)
{
if (ModelState.IsValid)
{
var employee = new Employee
{
FullName = vm.FullName,
Email = vm.Email,
DepartmentId = vm.DepartmentId,
DesignationId = vm.DesignationId,
HireDate = vm.HireDate,
DateOfBirth = vm.DateOfBirth,
EmployeeTypeId = vm.EmployeeTypeId,
Gender = vm.Gender,
Salary = vm.Salary
};
await _employeeService.CreateEmployeeAsync(employee);
return RedirectToAction("Success", new { id = employee.Id });
}
vm.Departments = await _employeeService.GetDepartmentsAsync();
vm.EmployeeTypes = await _employeeService.GetEmployeeTypesAsync();
vm.Designations = vm.DepartmentId != 0 ? await _employeeService.GetDesignationsByDepartmentAsync(vm.DepartmentId) : new List<Designation>();
return View(vm);
}
[HttpGet]
public async Task<IActionResult> Update(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
var vm = new EmployeeCreateUpdateViewModel
{
Id = employee.Id,
FullName = employee.FullName,
Email = employee.Email,
DepartmentId = employee.DepartmentId,
DesignationId = employee.DesignationId,
HireDate = employee.HireDate,
DateOfBirth = employee.DateOfBirth,
EmployeeTypeId = employee.EmployeeTypeId,
Gender = employee.Gender,
Salary = employee.Salary,
Departments = await _employeeService.GetDepartmentsAsync(),
EmployeeTypes = await _employeeService.GetEmployeeTypesAsync(),
Designations = await _employeeService.GetDesignationsByDepartmentAsync(employee.DepartmentId)
};
return View(vm);
}
[HttpPost]
public async Task<IActionResult> Update(EmployeeCreateUpdateViewModel vm)
{
if (ModelState.IsValid)
{
var employee = new Employee
{
Id = vm.Id!.Value,
FullName = vm.FullName,
Email = vm.Email,
DepartmentId = vm.DepartmentId,
DesignationId = vm.DesignationId,
HireDate = vm.HireDate,
DateOfBirth = vm.DateOfBirth,
EmployeeTypeId = vm.EmployeeTypeId,
Gender = vm.Gender,
Salary = vm.Salary
};
await _employeeService.UpdateEmployeeAsync(employee);
TempData["Message"] = $"Employee with ID {employee.Id} and Name {employee.FullName} has been updated.";
return RedirectToAction("List");
}
vm.Departments = await _employeeService.GetDepartmentsAsync();
vm.EmployeeTypes = await _employeeService.GetEmployeeTypesAsync();
vm.Designations = vm.DepartmentId != 0 ? await _employeeService.GetDesignationsByDepartmentAsync(vm.DepartmentId) : new List<Designation>();
return View(vm);
}
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
return View(employee);
}
[HttpPost, ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
await _employeeService.DeleteEmployeeAsync(id);
TempData["Message"] = $"Employee with ID {id} and Name {employee.FullName} has been deleted.";
return RedirectToAction("List");
}
[HttpGet]
public async Task<JsonResult> GetDesignations(int departmentId)
{
var designations = await _employeeService.GetDesignationsByDepartmentAsync(departmentId);
var result = designations.Select(d => new { id = d.Id, name = d.Name }).ToList();
return Json(result);
}
[HttpGet]
public async Task<IActionResult> Success(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
return View(employee);
}
[HttpGet]
public async Task<IActionResult> Details(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
if (employee == null) return NotFound();
return View(employee);
}
}
}
Creating Views:
Now, let us create the required views:
List View:
Next, create a view named List.cshtml within the Views/Employee folder, and then copy and paste the following code. This view displays a searchable, filterable, and paginated list of employees. It allows admins to quickly find employees by name, department, or type, and provides buttons to view details, edit, or delete each employee.
@model EmployeePortal.ViewModels.EmployeeListViewModel
ViewData["Title"] = "Employee List";
var pageSizeOptions = new List<int> { 3, 5, 10, 15, 20 };
<div class="container mt-1">
<div class="d-flex justify-content-between align-items-center mb-4 p-3 bg-light rounded shadow-sm">
<h2 class="mb-0 text-primary"><i class="bi bi-people-fill"></i> @ViewData["Title"]</h2>
<a class="btn btn-success btn-lg" asp-action="Create">
<i class="bi bi-plus-circle"></i> Create New Employee
@if (TempData["Message"] != null)
<div class="alert alert-success alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
<div class="card mb-4 shadow-sm">
<div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
<h5 class="mb-0">🔍 Filter Employees</h5>
<span class="badge bg-light text-dark">Total Employees: @Model.Total 📝</span>
<form method="get" asp-controller="Employee" asp-action="List" class="row g-3">
<label asp-for="SearchTerm" class="form-label">🔍 Search by Name</label>
<input asp-for="SearchTerm" class="form-control" placeholder="Type a name..." />
<label asp-for="SelectedDepartmentId" class="form-label">🖥️ Department</label>
<select asp-for="SelectedDepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control">
<option value="">All Departments</option>
<label asp-for="SelectedEmployeeTypeId" class="form-label">📅 Employee Type</label>
<select asp-for="SelectedEmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">All Employee Types</option>
<label asp-for="PageSize" class="form-label">📄 Items per Page</label>
<select asp-for="PageSize" asp-items="@(new SelectList(pageSizeOptions))" class="form-control" onchange="this.form.submit();">
<option value="">Select</option>
<div class="col-md-1 d-flex align-items-end">
<button type="submit" class="btn btn-success w-100">Filter</button>
<div class="card shadow-sm">
<div class="card-body p-0">
<table class="table table-hover table-striped mb-0">
<thead class="bg-primary text-white">
<th class="text-center">⚙️ Actions</th>
@if (Model.Employees != null && Model.Employees.Count > 0)
foreach (var employee in Model.Employees)
<td>@employee.FullName</td>
<td>@employee.Designation?.Name</td>
<td>@employee.Department?.Name</td>
<td>@employee.Gender</td>
<td>@employee.EmployeeType?.Name</td>
<a class="btn btn-sm btn-info" asp-controller="Employee" asp-action="Details" asp-route-id="@employee.Id" title="Details">
<i class="bi bi-eye"></i>
<a class="btn btn-sm btn-warning" asp-controller="Employee" asp-action="Update" asp-route-id="@employee.Id" title="Edit">
<i class="bi bi-pencil"></i>
<a class="btn btn-sm btn-danger" asp-controller="Employee" asp-action="Delete" asp-route-id="@employee.Id" title="Delete">
<i class="bi bi-trash"></i>
<td colspan="7" class="text-center text-muted">No employees found.</td>
<nav aria-label="Employee List Pagination" class="mt-4">
<ul class="pagination justify-content-center mb-0">
@if (Model.PageNumber == 1)
<li class="page-item disabled"><span class="page-link">First ⏮️</span></li>
<li class="page-item disabled"><span class="page-link">Previous ⬅️</span></li>
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(1))">First ⏮️</a></li>
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.PageNumber - 1))">Previous ⬅️</a></li>
<li class="page-item active"><span class="page-link">@Model.PageNumber</span></li>
@if (Model.PageNumber == Model.TotalPages)
<li class="page-item disabled"><span class="page-link">Next ➡️</span></li>
<li class="page-item disabled"><span class="page-link">Last ⏭️</span></li>
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.PageNumber + 1))">Next ➡️</a></li>
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.TotalPages))">Last ⏭️</a></li>
private object GetRouteValuesForPage(int pageNumber)
SearchTerm = Model.SearchTerm,
departmentId = Model.SelectedDepartmentId,
employeeTypeId = Model.SelectedEmployeeTypeId,
PageSize = Model.PageSize,
@model EmployeePortal.ViewModels.EmployeeListViewModel
@{
ViewData["Title"] = "Employee List";
var pageSizeOptions = new List<int> { 3, 5, 10, 15, 20 };
}
<div class="container mt-1">
<div class="row">
<div class="col-md-12">
<div class="d-flex justify-content-between align-items-center mb-4 p-3 bg-light rounded shadow-sm">
<h2 class="mb-0 text-primary"><i class="bi bi-people-fill"></i> @ViewData["Title"]</h2>
<a class="btn btn-success btn-lg" asp-action="Create">
<i class="bi bi-plus-circle"></i> Create New Employee
</a>
</div>
@if (TempData["Message"] != null)
{
<div class="alert alert-success alert-dismissible fade show" role="alert">
@TempData["Message"]
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
}
<!-- Filter Section -->
<div class="card mb-4 shadow-sm">
<div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
<h5 class="mb-0">🔍 Filter Employees</h5>
<span class="badge bg-light text-dark">Total Employees: @Model.Total 📝</span>
</div>
<div class="card-body">
<form method="get" asp-controller="Employee" asp-action="List" class="row g-3">
<div class="col-md-3">
<label asp-for="SearchTerm" class="form-label">🔍 Search by Name</label>
<input asp-for="SearchTerm" class="form-control" placeholder="Type a name..." />
</div>
<div class="col-md-3">
<label asp-for="SelectedDepartmentId" class="form-label">🖥️ Department</label>
<select asp-for="SelectedDepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control">
<option value="">All Departments</option>
</select>
</div>
<div class="col-md-3">
<label asp-for="SelectedEmployeeTypeId" class="form-label">📅 Employee Type</label>
<select asp-for="SelectedEmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">All Employee Types</option>
</select>
</div>
<div class="col-md-2">
<label asp-for="PageSize" class="form-label">📄 Items per Page</label>
<select asp-for="PageSize" asp-items="@(new SelectList(pageSizeOptions))" class="form-control" onchange="this.form.submit();">
<option value="">Select</option>
</select>
</div>
<div class="col-md-1 d-flex align-items-end">
<button type="submit" class="btn btn-success w-100">Filter</button>
</div>
</form>
</div>
</div>
<div class="card shadow-sm">
<div class="card-body p-0">
<table class="table table-hover table-striped mb-0">
<thead class="bg-primary text-white">
<tr>
<th>👤 Name</th>
<th>📩 Email</th>
<th>💼 Designation</th>
<th>🖥️ Department</th>
<th>⚧ Gender</th>
<th>📅 Employee Type</th>
<th class="text-center">⚙️ Actions</th>
</tr>
</thead>
<tbody>
@if (Model.Employees != null && Model.Employees.Count > 0)
{
foreach (var employee in Model.Employees)
{
<tr>
<td>@employee.FullName</td>
<td>@employee.Email</td>
<td>@employee.Designation?.Name</td>
<td>@employee.Department?.Name</td>
<td>@employee.Gender</td>
<td>@employee.EmployeeType?.Name</td>
<td class="text-center">
<a class="btn btn-sm btn-info" asp-controller="Employee" asp-action="Details" asp-route-id="@employee.Id" title="Details">
<i class="bi bi-eye"></i>
</a>
<a class="btn btn-sm btn-warning" asp-controller="Employee" asp-action="Update" asp-route-id="@employee.Id" title="Edit">
<i class="bi bi-pencil"></i>
</a>
<a class="btn btn-sm btn-danger" asp-controller="Employee" asp-action="Delete" asp-route-id="@employee.Id" title="Delete">
<i class="bi bi-trash"></i>
</a>
</td>
</tr>
}
}
else
{
<tr>
<td colspan="7" class="text-center text-muted">No employees found.</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<!-- Pagination -->
<nav aria-label="Employee List Pagination" class="mt-4">
<ul class="pagination justify-content-center mb-0">
@if (Model.PageNumber == 1)
{
<li class="page-item disabled"><span class="page-link">First ⏮️</span></li>
<li class="page-item disabled"><span class="page-link">Previous ⬅️</span></li>
}
else
{
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(1))">First ⏮️</a></li>
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.PageNumber - 1))">Previous ⬅️</a></li>
}
<li class="page-item active"><span class="page-link">@Model.PageNumber</span></li>
@if (Model.PageNumber == Model.TotalPages)
{
<li class="page-item disabled"><span class="page-link">Next ➡️</span></li>
<li class="page-item disabled"><span class="page-link">Last ⏭️</span></li>
}
else
{
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.PageNumber + 1))">Next ➡️</a></li>
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.TotalPages))">Last ⏭️</a></li>
}
</ul>
</nav>
</div>
</div>
</div>
@functions {
private object GetRouteValuesForPage(int pageNumber)
{
return new
{
SearchTerm = Model.SearchTerm,
departmentId = Model.SelectedDepartmentId,
employeeTypeId = Model.SelectedEmployeeTypeId,
PageSize = Model.PageSize,
PageNumber = pageNumber
};
}
}
@model EmployeePortal.ViewModels.EmployeeListViewModel
@{
ViewData["Title"] = "Employee List";
var pageSizeOptions = new List<int> { 3, 5, 10, 15, 20 };
}
<div class="container mt-1">
<div class="row">
<div class="col-md-12">
<div class="d-flex justify-content-between align-items-center mb-4 p-3 bg-light rounded shadow-sm">
<h2 class="mb-0 text-primary"><i class="bi bi-people-fill"></i> @ViewData["Title"]</h2>
<a class="btn btn-success btn-lg" asp-action="Create">
<i class="bi bi-plus-circle"></i> Create New Employee
</a>
</div>
@if (TempData["Message"] != null)
{
<div class="alert alert-success alert-dismissible fade show" role="alert">
@TempData["Message"]
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
}
<!-- Filter Section -->
<div class="card mb-4 shadow-sm">
<div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
<h5 class="mb-0">🔍 Filter Employees</h5>
<span class="badge bg-light text-dark">Total Employees: @Model.Total 📝</span>
</div>
<div class="card-body">
<form method="get" asp-controller="Employee" asp-action="List" class="row g-3">
<div class="col-md-3">
<label asp-for="SearchTerm" class="form-label">🔍 Search by Name</label>
<input asp-for="SearchTerm" class="form-control" placeholder="Type a name..." />
</div>
<div class="col-md-3">
<label asp-for="SelectedDepartmentId" class="form-label">🖥️ Department</label>
<select asp-for="SelectedDepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control">
<option value="">All Departments</option>
</select>
</div>
<div class="col-md-3">
<label asp-for="SelectedEmployeeTypeId" class="form-label">📅 Employee Type</label>
<select asp-for="SelectedEmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">All Employee Types</option>
</select>
</div>
<div class="col-md-2">
<label asp-for="PageSize" class="form-label">📄 Items per Page</label>
<select asp-for="PageSize" asp-items="@(new SelectList(pageSizeOptions))" class="form-control" onchange="this.form.submit();">
<option value="">Select</option>
</select>
</div>
<div class="col-md-1 d-flex align-items-end">
<button type="submit" class="btn btn-success w-100">Filter</button>
</div>
</form>
</div>
</div>
<div class="card shadow-sm">
<div class="card-body p-0">
<table class="table table-hover table-striped mb-0">
<thead class="bg-primary text-white">
<tr>
<th>👤 Name</th>
<th>📩 Email</th>
<th>💼 Designation</th>
<th>🖥️ Department</th>
<th>⚧ Gender</th>
<th>📅 Employee Type</th>
<th class="text-center">⚙️ Actions</th>
</tr>
</thead>
<tbody>
@if (Model.Employees != null && Model.Employees.Count > 0)
{
foreach (var employee in Model.Employees)
{
<tr>
<td>@employee.FullName</td>
<td>@employee.Email</td>
<td>@employee.Designation?.Name</td>
<td>@employee.Department?.Name</td>
<td>@employee.Gender</td>
<td>@employee.EmployeeType?.Name</td>
<td class="text-center">
<a class="btn btn-sm btn-info" asp-controller="Employee" asp-action="Details" asp-route-id="@employee.Id" title="Details">
<i class="bi bi-eye"></i>
</a>
<a class="btn btn-sm btn-warning" asp-controller="Employee" asp-action="Update" asp-route-id="@employee.Id" title="Edit">
<i class="bi bi-pencil"></i>
</a>
<a class="btn btn-sm btn-danger" asp-controller="Employee" asp-action="Delete" asp-route-id="@employee.Id" title="Delete">
<i class="bi bi-trash"></i>
</a>
</td>
</tr>
}
}
else
{
<tr>
<td colspan="7" class="text-center text-muted">No employees found.</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<!-- Pagination -->
<nav aria-label="Employee List Pagination" class="mt-4">
<ul class="pagination justify-content-center mb-0">
@if (Model.PageNumber == 1)
{
<li class="page-item disabled"><span class="page-link">First ⏮️</span></li>
<li class="page-item disabled"><span class="page-link">Previous ⬅️</span></li>
}
else
{
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(1))">First ⏮️</a></li>
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.PageNumber - 1))">Previous ⬅️</a></li>
}
<li class="page-item active"><span class="page-link">@Model.PageNumber</span></li>
@if (Model.PageNumber == Model.TotalPages)
{
<li class="page-item disabled"><span class="page-link">Next ➡️</span></li>
<li class="page-item disabled"><span class="page-link">Last ⏭️</span></li>
}
else
{
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.PageNumber + 1))">Next ➡️</a></li>
<li class="page-item"><a class="page-link" href="@Url.Action("List", "Employee", GetRouteValuesForPage(Model.TotalPages))">Last ⏭️</a></li>
}
</ul>
</nav>
</div>
</div>
</div>
@functions {
private object GetRouteValuesForPage(int pageNumber)
{
return new
{
SearchTerm = Model.SearchTerm,
departmentId = Model.SelectedDepartmentId,
employeeTypeId = Model.SelectedEmployeeTypeId,
PageSize = Model.PageSize,
PageNumber = pageNumber
};
}
}
Create View:
Next, create a view named Create.cshtml within the Views/Employee folder and then copy and paste the following code. This view shows a form for adding a new employee. Users can enter all required details, and the form validates inputs before submitting. It includes dropdowns that dynamically update based on selections, such as designations changing when a department is chosen.
@model EmployeePortal.ViewModels.EmployeeCreateUpdateViewModel
ViewData["Title"] = "Create New Employee";
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-2 border rounded">
<div class="bg-primary text-white text-center py-3 rounded mb-4 shadow-sm">
<h2 class="mb-0">👤 Create New Employee</h2>
<form asp-action="Create" method="post">
<label asp-for="FullName" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="FullName" class="form-control" placeholder="Enter full name" />
<span asp-validation-for="FullName" class="text-danger"></span>
<label asp-for="Email" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="Email" class="form-control" placeholder="Enter email address" />
<span asp-validation-for="Email" class="text-danger"></span>
<label asp-for="DepartmentId" class="col-sm-3 col-form-label text-end"></label>
<select asp-for="DepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control" id="DepartmentDropdown">
<option value="">Select Department</option>
<span asp-validation-for="DepartmentId" class="text-danger"></span>
<label asp-for="DesignationId" class="col-sm-3 col-form-label text-end"></label>
<select asp-for="DesignationId" asp-items="@(new SelectList(Model.Designations, "Id", "Name"))" class="form-control" id="DesignationDropdown">
<option value="">Select Designation</option>
<span asp-validation-for="DesignationId" class="text-danger"></span>
<label asp-for="HireDate" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="HireDate" class="form-control" type="date" />
<span asp-validation-for="HireDate" class="text-danger"></span>
<label asp-for="DateOfBirth" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="DateOfBirth" class="form-control" type="date" />
<span asp-validation-for="DateOfBirth" class="text-danger"></span>
<label asp-for="EmployeeTypeId" class="col-sm-3 col-form-label text-end"></label>
<select asp-for="EmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">Select Employee Type</option>
<span asp-validation-for="EmployeeTypeId" class="text-danger"></span>
<label asp-for="Gender" class="col-sm-3 col-form-label text-end"></label>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Male" />
<label class="form-check-label">Male</label>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Female" />
<label class="form-check-label">Female</label>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Other" />
<label class="form-check-label">Other</label>
<span asp-validation-for="Gender" class="text-danger"></span>
<label asp-for="Salary" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="Salary" class="form-control" placeholder="Enter salary" />
<span asp-validation-for="Salary" class="text-danger"></span>
<div class="text-center mt-4">
<button type="submit" class="btn btn-success btn-lg me-3">Create</button>
<a class="btn btn-primary btn-lg" asp-action="List">Back</a>
$(document).ready(function () {
function loadDesignations(departmentId, selectedDesignationId) {
$.getJSON('@Url.Action("GetDesignations")', { departmentId: departmentId }, function (data) {
var $designationDropdown = $('#DesignationDropdown');
$designationDropdown.empty();
$designationDropdown.append('<option value="">Select Designation</option>');
$.each(data, function (index, item) {
var selected = item.id === selectedDesignationId ? 'selected' : '';
$designationDropdown.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
$('#DesignationDropdown').empty().append('<option value="">Select Designation</option>');
var departmentId = $('#DepartmentDropdown').val();
var selectedDesignationId = '@Model.DesignationId';
loadDesignations(parseInt(departmentId), parseInt(selectedDesignationId));
$('#DepartmentDropdown').change(function () {
var deptId = $(this).val();
loadDesignations(parseInt(deptId), null);
@model EmployeePortal.ViewModels.EmployeeCreateUpdateViewModel
@{
ViewData["Title"] = "Create New Employee";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-2 border rounded">
<div class="bg-primary text-white text-center py-3 rounded mb-4 shadow-sm">
<h2 class="mb-0">👤 Create New Employee</h2>
</div>
<form asp-action="Create" method="post">
<div class="row mb-3">
<label asp-for="FullName" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="FullName" class="form-control" placeholder="Enter full name" />
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Email" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="Email" class="form-control" placeholder="Enter email address" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DepartmentId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="DepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control" id="DepartmentDropdown">
<option value="">Select Department</option>
</select>
<span asp-validation-for="DepartmentId" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DesignationId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="DesignationId" asp-items="@(new SelectList(Model.Designations, "Id", "Name"))" class="form-control" id="DesignationDropdown">
<option value="">Select Designation</option>
</select>
<span asp-validation-for="DesignationId" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="HireDate" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="HireDate" class="form-control" type="date" />
<span asp-validation-for="HireDate" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DateOfBirth" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="DateOfBirth" class="form-control" type="date" />
<span asp-validation-for="DateOfBirth" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="EmployeeTypeId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="EmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">Select Employee Type</option>
</select>
<span asp-validation-for="EmployeeTypeId" class="text-danger"></span>
</div>
</div>
<div class="mb-3 row">
<label asp-for="Gender" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Male" />
<label class="form-check-label">Male</label>
</div>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Female" />
<label class="form-check-label">Female</label>
</div>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Other" />
<label class="form-check-label">Other</label>
</div>
<span asp-validation-for="Gender" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Salary" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="Salary" class="form-control" placeholder="Enter salary" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
</div>
<div class="text-center mt-4">
<button type="submit" class="btn btn-success btn-lg me-3">Create</button>
<a class="btn btn-primary btn-lg" asp-action="List">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
$(document).ready(function () {
function loadDesignations(departmentId, selectedDesignationId) {
if (departmentId) {
$.getJSON('@Url.Action("GetDesignations")', { departmentId: departmentId }, function (data) {
var $designationDropdown = $('#DesignationDropdown');
$designationDropdown.empty();
$designationDropdown.append('<option value="">Select Designation</option>');
$.each(data, function (index, item) {
var selected = item.id === selectedDesignationId ? 'selected' : '';
$designationDropdown.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
});
});
} else {
$('#DesignationDropdown').empty().append('<option value="">Select Designation</option>');
}
}
var departmentId = $('#DepartmentDropdown').val();
var selectedDesignationId = '@Model.DesignationId';
if (departmentId) {
loadDesignations(parseInt(departmentId), parseInt(selectedDesignationId));
}
$('#DepartmentDropdown').change(function () {
var deptId = $(this).val();
loadDesignations(parseInt(deptId), null);
});
});
</script>
}
@model EmployeePortal.ViewModels.EmployeeCreateUpdateViewModel
@{
ViewData["Title"] = "Create New Employee";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-2 border rounded">
<div class="bg-primary text-white text-center py-3 rounded mb-4 shadow-sm">
<h2 class="mb-0">👤 Create New Employee</h2>
</div>
<form asp-action="Create" method="post">
<div class="row mb-3">
<label asp-for="FullName" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="FullName" class="form-control" placeholder="Enter full name" />
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Email" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="Email" class="form-control" placeholder="Enter email address" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DepartmentId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="DepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control" id="DepartmentDropdown">
<option value="">Select Department</option>
</select>
<span asp-validation-for="DepartmentId" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DesignationId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="DesignationId" asp-items="@(new SelectList(Model.Designations, "Id", "Name"))" class="form-control" id="DesignationDropdown">
<option value="">Select Designation</option>
</select>
<span asp-validation-for="DesignationId" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="HireDate" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="HireDate" class="form-control" type="date" />
<span asp-validation-for="HireDate" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DateOfBirth" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="DateOfBirth" class="form-control" type="date" />
<span asp-validation-for="DateOfBirth" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="EmployeeTypeId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="EmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">Select Employee Type</option>
</select>
<span asp-validation-for="EmployeeTypeId" class="text-danger"></span>
</div>
</div>
<div class="mb-3 row">
<label asp-for="Gender" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Male" />
<label class="form-check-label">Male</label>
</div>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Female" />
<label class="form-check-label">Female</label>
</div>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Other" />
<label class="form-check-label">Other</label>
</div>
<span asp-validation-for="Gender" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Salary" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="Salary" class="form-control" placeholder="Enter salary" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
</div>
<div class="text-center mt-4">
<button type="submit" class="btn btn-success btn-lg me-3">Create</button>
<a class="btn btn-primary btn-lg" asp-action="List">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
$(document).ready(function () {
function loadDesignations(departmentId, selectedDesignationId) {
if (departmentId) {
$.getJSON('@Url.Action("GetDesignations")', { departmentId: departmentId }, function (data) {
var $designationDropdown = $('#DesignationDropdown');
$designationDropdown.empty();
$designationDropdown.append('<option value="">Select Designation</option>');
$.each(data, function (index, item) {
var selected = item.id === selectedDesignationId ? 'selected' : '';
$designationDropdown.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
});
});
} else {
$('#DesignationDropdown').empty().append('<option value="">Select Designation</option>');
}
}
var departmentId = $('#DepartmentDropdown').val();
var selectedDesignationId = '@Model.DesignationId';
if (departmentId) {
loadDesignations(parseInt(departmentId), parseInt(selectedDesignationId));
}
$('#DepartmentDropdown').change(function () {
var deptId = $(this).val();
loadDesignations(parseInt(deptId), null);
});
});
</script>
}
Success View:
Next, create a view named Success.cshtml within the Views/Employee folder, and then copy and paste the following code. This view confirms that a new employee was successfully created. It displays the employee’s details and offers buttons to either add another employee or go back to the employee list.
@model EmployeePortal.Models.Employee
ViewData["Title"] = "Employee Created Successfully";
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-4 border rounded">
<div class="text-center mb-4">
<h2 class="text-success mb-3"><i class="bi bi-check-circle-fill"></i> Employee Created Successfully!</h2>
Welcome <strong>@Model.FullName</strong>! We are excited to have you join the <strong>@Model.Department?.Name</strong> department. Below are the details of the newly created employee:
<div class="table-responsive">
<table class="table table-borderless">
<th class="text-muted text-start" style="width: 30%;">📧 Email:</th>
<td class="fw-bold text-dark text-start">@Model.Email</td>
<th class="text-muted text-start">💼 Designation:</th>
<td class="fw-bold text-dark text-start">@Model.Designation?.Name</td>
<th class="text-muted text-start">🏢 Department:</th>
<td class="fw-bold text-dark text-start">@Model.Department?.Name</td>
<th class="text-muted text-start">🗓️ Hire Date:</th>
<td class="fw-bold text-dark text-start">@Model.HireDate.ToShortDateString()</td>
<th class="text-muted text-start">🎂 Date of Birth:</th>
<td class="fw-bold text-dark text-start">@Model.DateOfBirth.ToShortDateString()</td>
<th class="text-muted text-start">👔 Employee Type:</th>
<td class="fw-bold text-dark text-start">@Model.EmployeeType?.Name</td>
<th class="text-muted text-start">⚧ Gender:</th>
<td class="fw-bold text-dark text-start">@Model.Gender</td>
<th class="text-muted text-start">💰 Salary:</th>
<td class="fw-bold text-dark text-start">$@Model.Salary.ToString("N2")</td>
<div class="text-center mt-4">
<a class="btn btn-success btn-lg me-3" asp-action="Create">
<i class="bi bi-person-plus-fill"></i> Create Another Employee
<a class="btn btn-primary btn-lg" asp-action="List">
<i class="bi bi-arrow-left-circle-fill"></i> Back to Employee List
@model EmployeePortal.Models.Employee
@{
ViewData["Title"] = "Employee Created Successfully";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-4 border rounded">
<div class="text-center mb-4">
<h2 class="text-success mb-3"><i class="bi bi-check-circle-fill"></i> Employee Created Successfully!</h2>
<p class="text-muted">
Welcome <strong>@Model.FullName</strong>! We are excited to have you join the <strong>@Model.Department?.Name</strong> department. Below are the details of the newly created employee:
</p>
</div>
<div class="table-responsive">
<table class="table table-borderless">
<tbody>
<tr>
<th class="text-muted text-start" style="width: 30%;">📧 Email:</th>
<td class="fw-bold text-dark text-start">@Model.Email</td>
</tr>
<tr>
<th class="text-muted text-start">💼 Designation:</th>
<td class="fw-bold text-dark text-start">@Model.Designation?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">🏢 Department:</th>
<td class="fw-bold text-dark text-start">@Model.Department?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">🗓️ Hire Date:</th>
<td class="fw-bold text-dark text-start">@Model.HireDate.ToShortDateString()</td>
</tr>
<tr>
<th class="text-muted text-start">🎂 Date of Birth:</th>
<td class="fw-bold text-dark text-start">@Model.DateOfBirth.ToShortDateString()</td>
</tr>
<tr>
<th class="text-muted text-start">👔 Employee Type:</th>
<td class="fw-bold text-dark text-start">@Model.EmployeeType?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">⚧ Gender:</th>
<td class="fw-bold text-dark text-start">@Model.Gender</td>
</tr>
<tr>
<th class="text-muted text-start">💰 Salary:</th>
<td class="fw-bold text-dark text-start">$@Model.Salary.ToString("N2")</td>
</tr>
</tbody>
</table>
</div>
<div class="text-center mt-4">
<a class="btn btn-success btn-lg me-3" asp-action="Create">
<i class="bi bi-person-plus-fill"></i> Create Another Employee
</a>
<a class="btn btn-primary btn-lg" asp-action="List">
<i class="bi bi-arrow-left-circle-fill"></i> Back to Employee List
</a>
</div>
</div>
</div>
</div>
</div>
</div>
@model EmployeePortal.Models.Employee
@{
ViewData["Title"] = "Employee Created Successfully";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-4 border rounded">
<div class="text-center mb-4">
<h2 class="text-success mb-3"><i class="bi bi-check-circle-fill"></i> Employee Created Successfully!</h2>
<p class="text-muted">
Welcome <strong>@Model.FullName</strong>! We are excited to have you join the <strong>@Model.Department?.Name</strong> department. Below are the details of the newly created employee:
</p>
</div>
<div class="table-responsive">
<table class="table table-borderless">
<tbody>
<tr>
<th class="text-muted text-start" style="width: 30%;">📧 Email:</th>
<td class="fw-bold text-dark text-start">@Model.Email</td>
</tr>
<tr>
<th class="text-muted text-start">💼 Designation:</th>
<td class="fw-bold text-dark text-start">@Model.Designation?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">🏢 Department:</th>
<td class="fw-bold text-dark text-start">@Model.Department?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">🗓️ Hire Date:</th>
<td class="fw-bold text-dark text-start">@Model.HireDate.ToShortDateString()</td>
</tr>
<tr>
<th class="text-muted text-start">🎂 Date of Birth:</th>
<td class="fw-bold text-dark text-start">@Model.DateOfBirth.ToShortDateString()</td>
</tr>
<tr>
<th class="text-muted text-start">👔 Employee Type:</th>
<td class="fw-bold text-dark text-start">@Model.EmployeeType?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">⚧ Gender:</th>
<td class="fw-bold text-dark text-start">@Model.Gender</td>
</tr>
<tr>
<th class="text-muted text-start">💰 Salary:</th>
<td class="fw-bold text-dark text-start">$@Model.Salary.ToString("N2")</td>
</tr>
</tbody>
</table>
</div>
<div class="text-center mt-4">
<a class="btn btn-success btn-lg me-3" asp-action="Create">
<i class="bi bi-person-plus-fill"></i> Create Another Employee
</a>
<a class="btn btn-primary btn-lg" asp-action="List">
<i class="bi bi-arrow-left-circle-fill"></i> Back to Employee List
</a>
</div>
</div>
</div>
</div>
</div>
</div>
Details View:
Next, create a view named Details.cshtml within the Views/Employee folder, and then copy and paste the following code. This view presents detailed information about a selected employee in a clean, readable format. It provides action buttons to update or delete the employee or return to the employee list.
@model EmployeePortal.Models.Employee
ViewData["Title"] = "Employee Details";
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card shadow-sm border rounded">
<div class="card-header bg-primary text-white text-center py-3">
<i class="bi bi-person-circle me-2"></i> @Model.FullName
<small class="fst-italic">Employee ID: <span class="fw-semibold">@Model.Id</span></small>
<div class="card-body p-4">
<div class="table-responsive">
<table class="table table-borderless mb-0">
<th class="text-muted" style="width: 30%;">📧 Email</th>
<a href="mailto:@Model.Email" class="text-decoration-none fw-semibold text-primary">
<th class="text-muted">💼 Designation</th>
<td class="fw-semibold">@Model.Designation?.Name</td>
<th class="text-muted">🏢 Department</th>
<td class="fw-semibold">@Model.Department?.Name</td>
<th class="text-muted">🗓️ Hire Date</th>
<td class="fw-semibold">@Model.HireDate.ToString("MMMM dd, yyyy")</td>
<th class="text-muted">🎂 Date of Birth</th>
<td class="fw-semibold">@Model.DateOfBirth.ToString("MMMM dd, yyyy")</td>
<th class="text-muted">👔 Employee Type</th>
<td class="fw-semibold">@Model.EmployeeType?.Name</td>
<th class="text-muted">⚧ Gender</th>
<td class="fw-semibold">@Model.Gender</td>
<th class="text-muted">💰 Salary</th>
<td class="fw-semibold">$@Model.Salary.ToString("N2")</td>
<div class="d-flex justify-content-center gap-3 mt-4">
<a class="btn btn-success btn-lg px-4 rounded-pill shadow-sm" asp-action="Update" asp-route-id="@Model.Id">
<i class="bi bi-pencil-fill me-2"></i> Update
<a class="btn btn-danger btn-lg px-4 rounded-pill shadow-sm" asp-action="Delete" asp-route-id="@Model.Id">
<i class="bi bi-trash-fill me-2"></i> Delete
<a class="btn btn-info btn-lg px-4 rounded-pill shadow-sm text-white" asp-action="List">
<i class="bi bi-arrow-left-circle-fill me-2"></i> Back to List
@model EmployeePortal.Models.Employee
@{
ViewData["Title"] = "Employee Details";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card shadow-sm border rounded">
<div class="card-header bg-primary text-white text-center py-3">
<h2 class="mb-0">
<i class="bi bi-person-circle me-2"></i> @Model.FullName
</h2>
<small class="fst-italic">Employee ID: <span class="fw-semibold">@Model.Id</span></small>
</div>
<div class="card-body p-4">
<div class="table-responsive">
<table class="table table-borderless mb-0">
<tbody>
<tr>
<th class="text-muted" style="width: 30%;">📧 Email</th>
<td>
<a href="mailto:@Model.Email" class="text-decoration-none fw-semibold text-primary">
@Model.Email
</a>
</td>
</tr>
<tr>
<th class="text-muted">💼 Designation</th>
<td class="fw-semibold">@Model.Designation?.Name</td>
</tr>
<tr>
<th class="text-muted">🏢 Department</th>
<td class="fw-semibold">@Model.Department?.Name</td>
</tr>
<tr>
<th class="text-muted">🗓️ Hire Date</th>
<td class="fw-semibold">@Model.HireDate.ToString("MMMM dd, yyyy")</td>
</tr>
<tr>
<th class="text-muted">🎂 Date of Birth</th>
<td class="fw-semibold">@Model.DateOfBirth.ToString("MMMM dd, yyyy")</td>
</tr>
<tr>
<th class="text-muted">👔 Employee Type</th>
<td class="fw-semibold">@Model.EmployeeType?.Name</td>
</tr>
<tr>
<th class="text-muted">⚧ Gender</th>
<td class="fw-semibold">@Model.Gender</td>
</tr>
<tr>
<th class="text-muted">💰 Salary</th>
<td class="fw-semibold">$@Model.Salary.ToString("N2")</td>
</tr>
</tbody>
</table>
</div>
<div class="d-flex justify-content-center gap-3 mt-4">
<a class="btn btn-success btn-lg px-4 rounded-pill shadow-sm" asp-action="Update" asp-route-id="@Model.Id">
<i class="bi bi-pencil-fill me-2"></i> Update
</a>
<a class="btn btn-danger btn-lg px-4 rounded-pill shadow-sm" asp-action="Delete" asp-route-id="@Model.Id">
<i class="bi bi-trash-fill me-2"></i> Delete
</a>
<a class="btn btn-info btn-lg px-4 rounded-pill shadow-sm text-white" asp-action="List">
<i class="bi bi-arrow-left-circle-fill me-2"></i> Back to List
</a>
</div>
</div>
</div>
</div>
</div>
</div>
@model EmployeePortal.Models.Employee
@{
ViewData["Title"] = "Employee Details";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card shadow-sm border rounded">
<div class="card-header bg-primary text-white text-center py-3">
<h2 class="mb-0">
<i class="bi bi-person-circle me-2"></i> @Model.FullName
</h2>
<small class="fst-italic">Employee ID: <span class="fw-semibold">@Model.Id</span></small>
</div>
<div class="card-body p-4">
<div class="table-responsive">
<table class="table table-borderless mb-0">
<tbody>
<tr>
<th class="text-muted" style="width: 30%;">📧 Email</th>
<td>
<a href="mailto:@Model.Email" class="text-decoration-none fw-semibold text-primary">
@Model.Email
</a>
</td>
</tr>
<tr>
<th class="text-muted">💼 Designation</th>
<td class="fw-semibold">@Model.Designation?.Name</td>
</tr>
<tr>
<th class="text-muted">🏢 Department</th>
<td class="fw-semibold">@Model.Department?.Name</td>
</tr>
<tr>
<th class="text-muted">🗓️ Hire Date</th>
<td class="fw-semibold">@Model.HireDate.ToString("MMMM dd, yyyy")</td>
</tr>
<tr>
<th class="text-muted">🎂 Date of Birth</th>
<td class="fw-semibold">@Model.DateOfBirth.ToString("MMMM dd, yyyy")</td>
</tr>
<tr>
<th class="text-muted">👔 Employee Type</th>
<td class="fw-semibold">@Model.EmployeeType?.Name</td>
</tr>
<tr>
<th class="text-muted">⚧ Gender</th>
<td class="fw-semibold">@Model.Gender</td>
</tr>
<tr>
<th class="text-muted">💰 Salary</th>
<td class="fw-semibold">$@Model.Salary.ToString("N2")</td>
</tr>
</tbody>
</table>
</div>
<div class="d-flex justify-content-center gap-3 mt-4">
<a class="btn btn-success btn-lg px-4 rounded-pill shadow-sm" asp-action="Update" asp-route-id="@Model.Id">
<i class="bi bi-pencil-fill me-2"></i> Update
</a>
<a class="btn btn-danger btn-lg px-4 rounded-pill shadow-sm" asp-action="Delete" asp-route-id="@Model.Id">
<i class="bi bi-trash-fill me-2"></i> Delete
</a>
<a class="btn btn-info btn-lg px-4 rounded-pill shadow-sm text-white" asp-action="List">
<i class="bi bi-arrow-left-circle-fill me-2"></i> Back to List
</a>
</div>
</div>
</div>
</div>
</div>
</div>
Update View:
Next, create a view named Update.cshtml within the Views/Employee folder and then copy and paste the following code. This view shows a form pre-filled with an employee’s existing details, allowing users to modify the information. Like the create view, it includes validation and dynamically updated dropdowns to ensure accurate data entry.
@model EmployeePortal.ViewModels.EmployeeCreateUpdateViewModel
ViewData["Title"] = "Update Employee";
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-2 border rounded">
<div class="bg-primary text-white text-center py-3 rounded mb-4 shadow-sm">
<h2 class="mb-0">Update Employee Details</h2>
<form asp-action="Update" method="post">
<!-- Hidden field to store the Employee ID -->
<input type="hidden" asp-for="Id" />
<label asp-for="FullName" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="FullName" class="form-control" placeholder="Enter full name" />
<span asp-validation-for="FullName" class="text-danger"></span>
<label asp-for="Email" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="Email" class="form-control" placeholder="Enter email address" />
<span asp-validation-for="Email" class="text-danger"></span>
<label asp-for="DepartmentId" class="col-sm-3 col-form-label text-end"></label>
<select asp-for="DepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control" id="DepartmentDropdown">
<option value="">Select Department</option>
<span asp-validation-for="DepartmentId" class="text-danger"></span>
<label asp-for="DesignationId" class="col-sm-3 col-form-label text-end"></label>
<select asp-for="DesignationId" asp-items="@(new SelectList(Model.Designations, "Id", "Name"))" class="form-control" id="DesignationDropdown">
<option value="">Select Designation</option>
<span asp-validation-for="DesignationId" class="text-danger"></span>
<label asp-for="HireDate" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="HireDate" class="form-control" type="date" />
<span asp-validation-for="HireDate" class="text-danger"></span>
<label asp-for="DateOfBirth" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="DateOfBirth" class="form-control" type="date" />
<span asp-validation-for="DateOfBirth" class="text-danger"></span>
<label asp-for="EmployeeTypeId" class="col-sm-3 col-form-label text-end"></label>
<select asp-for="EmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">Select Employee Type</option>
<span asp-validation-for="EmployeeTypeId" class="text-danger"></span>
<label asp-for="Gender" class="col-sm-3 col-form-label text-end"></label>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Male" />
<label class="form-check-label">Male</label>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Female" />
<label class="form-check-label">Female</label>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Other" />
<label class="form-check-label">Other</label>
<span asp-validation-for="Gender" class="text-danger"></span>
<label asp-for="Salary" class="col-sm-3 col-form-label text-end"></label>
<input asp-for="Salary" class="form-control" placeholder="Enter salary" />
<span asp-validation-for="Salary" class="text-danger"></span>
<div class="text-center mt-4">
<button type="submit" class="btn btn-success btn-lg me-3">Update</button>
<a class="btn btn-primary btn-lg" asp-action="List">Back</a>
$(document).ready(function () {
function loadDesignations(departmentId, selectedDesignationId) {
$.getJSON('@Url.Action("GetDesignations")', { departmentId: departmentId }, function (data) {
var $designationDropdown = $('#DesignationDropdown');
$designationDropdown.empty();
$designationDropdown.append('<option value="">Select Designation</option>');
$.each(data, function (index, item) {
var selected = item.id === selectedDesignationId ? 'selected' : '';
$designationDropdown.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
$('#DesignationDropdown').empty().append('<option value="">Select Designation</option>');
var departmentId = $('#DepartmentDropdown').val();
var selectedDesignationId = '@Model.DesignationId';
loadDesignations(parseInt(departmentId), parseInt(selectedDesignationId));
$('#DepartmentDropdown').change(function () {
var deptId = $(this).val();
loadDesignations(parseInt(deptId), null);
@model EmployeePortal.ViewModels.EmployeeCreateUpdateViewModel
@{
ViewData["Title"] = "Update Employee";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-2 border rounded">
<div class="bg-primary text-white text-center py-3 rounded mb-4 shadow-sm">
<h2 class="mb-0">Update Employee Details</h2>
</div>
<form asp-action="Update" method="post">
<!-- Hidden field to store the Employee ID -->
<input type="hidden" asp-for="Id" />
<div class="row mb-3">
<label asp-for="FullName" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="FullName" class="form-control" placeholder="Enter full name" />
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Email" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="Email" class="form-control" placeholder="Enter email address" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DepartmentId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="DepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control" id="DepartmentDropdown">
<option value="">Select Department</option>
</select>
<span asp-validation-for="DepartmentId" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DesignationId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="DesignationId" asp-items="@(new SelectList(Model.Designations, "Id", "Name"))" class="form-control" id="DesignationDropdown">
<option value="">Select Designation</option>
</select>
<span asp-validation-for="DesignationId" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="HireDate" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="HireDate" class="form-control" type="date" />
<span asp-validation-for="HireDate" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DateOfBirth" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="DateOfBirth" class="form-control" type="date" />
<span asp-validation-for="DateOfBirth" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="EmployeeTypeId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="EmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">Select Employee Type</option>
</select>
<span asp-validation-for="EmployeeTypeId" class="text-danger"></span>
</div>
</div>
<div class="mb-3 row">
<label asp-for="Gender" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Male" />
<label class="form-check-label">Male</label>
</div>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Female" />
<label class="form-check-label">Female</label>
</div>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Other" />
<label class="form-check-label">Other</label>
</div>
<span asp-validation-for="Gender" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Salary" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="Salary" class="form-control" placeholder="Enter salary" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
</div>
<div class="text-center mt-4">
<button type="submit" class="btn btn-success btn-lg me-3">Update</button>
<a class="btn btn-primary btn-lg" asp-action="List">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
$(document).ready(function () {
function loadDesignations(departmentId, selectedDesignationId) {
if (departmentId) {
$.getJSON('@Url.Action("GetDesignations")', { departmentId: departmentId }, function (data) {
var $designationDropdown = $('#DesignationDropdown');
$designationDropdown.empty();
$designationDropdown.append('<option value="">Select Designation</option>');
$.each(data, function (index, item) {
var selected = item.id === selectedDesignationId ? 'selected' : '';
$designationDropdown.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
});
});
} else {
$('#DesignationDropdown').empty().append('<option value="">Select Designation</option>');
}
}
var departmentId = $('#DepartmentDropdown').val();
var selectedDesignationId = '@Model.DesignationId';
if (departmentId) {
loadDesignations(parseInt(departmentId), parseInt(selectedDesignationId));
}
$('#DepartmentDropdown').change(function () {
var deptId = $(this).val();
loadDesignations(parseInt(deptId), null);
});
});
</script>
}
@model EmployeePortal.ViewModels.EmployeeCreateUpdateViewModel
@{
ViewData["Title"] = "Update Employee";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-2 border rounded">
<div class="bg-primary text-white text-center py-3 rounded mb-4 shadow-sm">
<h2 class="mb-0">Update Employee Details</h2>
</div>
<form asp-action="Update" method="post">
<!-- Hidden field to store the Employee ID -->
<input type="hidden" asp-for="Id" />
<div class="row mb-3">
<label asp-for="FullName" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="FullName" class="form-control" placeholder="Enter full name" />
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Email" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="Email" class="form-control" placeholder="Enter email address" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DepartmentId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="DepartmentId" asp-items="@(new SelectList(Model.Departments, "Id", "Name"))" class="form-control" id="DepartmentDropdown">
<option value="">Select Department</option>
</select>
<span asp-validation-for="DepartmentId" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DesignationId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="DesignationId" asp-items="@(new SelectList(Model.Designations, "Id", "Name"))" class="form-control" id="DesignationDropdown">
<option value="">Select Designation</option>
</select>
<span asp-validation-for="DesignationId" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="HireDate" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="HireDate" class="form-control" type="date" />
<span asp-validation-for="HireDate" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="DateOfBirth" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="DateOfBirth" class="form-control" type="date" />
<span asp-validation-for="DateOfBirth" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="EmployeeTypeId" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<select asp-for="EmployeeTypeId" asp-items="@(new SelectList(Model.EmployeeTypes, "Id", "Name"))" class="form-control">
<option value="">Select Employee Type</option>
</select>
<span asp-validation-for="EmployeeTypeId" class="text-danger"></span>
</div>
</div>
<div class="mb-3 row">
<label asp-for="Gender" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Male" />
<label class="form-check-label">Male</label>
</div>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Female" />
<label class="form-check-label">Female</label>
</div>
<div class="form-check form-check-inline">
<input asp-for="Gender" type="radio" class="form-check-input" value="Other" />
<label class="form-check-label">Other</label>
</div>
<span asp-validation-for="Gender" class="text-danger"></span>
</div>
</div>
<div class="row mb-3">
<label asp-for="Salary" class="col-sm-3 col-form-label text-end"></label>
<div class="col-sm-9">
<input asp-for="Salary" class="form-control" placeholder="Enter salary" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
</div>
<div class="text-center mt-4">
<button type="submit" class="btn btn-success btn-lg me-3">Update</button>
<a class="btn btn-primary btn-lg" asp-action="List">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
$(document).ready(function () {
function loadDesignations(departmentId, selectedDesignationId) {
if (departmentId) {
$.getJSON('@Url.Action("GetDesignations")', { departmentId: departmentId }, function (data) {
var $designationDropdown = $('#DesignationDropdown');
$designationDropdown.empty();
$designationDropdown.append('<option value="">Select Designation</option>');
$.each(data, function (index, item) {
var selected = item.id === selectedDesignationId ? 'selected' : '';
$designationDropdown.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
});
});
} else {
$('#DesignationDropdown').empty().append('<option value="">Select Designation</option>');
}
}
var departmentId = $('#DepartmentDropdown').val();
var selectedDesignationId = '@Model.DesignationId';
if (departmentId) {
loadDesignations(parseInt(departmentId), parseInt(selectedDesignationId));
}
$('#DepartmentDropdown').change(function () {
var deptId = $(this).val();
loadDesignations(parseInt(deptId), null);
});
});
</script>
}
Delete View:
Next, create a view named Delete.cshtml within the Views/Employee folder and then copy and paste the following code. This view asks users to confirm before deleting an employee. It displays key employee details, allowing users to double-check before permanently removing the record. Buttons are provided to confirm deletion, cancel, and return to the list.
@model EmployeePortal.Models.Employee
ViewData["Title"] = "Delete Employee";
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-4 border rounded">
<div class="text-center mb-4">
<h2 class="text-danger mb-3"><i class="bi bi-exclamation-triangle-fill"></i> Confirm Delete</h2>
<p class="lead">Are you sure you want to delete the following employee?</p>
<h3 class="text-primary">@Model.FullName</h3>
<div class="table-responsive mb-4">
<table class="table table-borderless">
<th class="text-muted text-start" style="width: 30%;">📧 Email:</th>
<td class="fw-bold text-dark text-start">@Model.Email</td>
<th class="text-muted text-start">💼 Designation:</th>
<td class="fw-bold text-dark text-start">@Model.Designation?.Name</td>
<th class="text-muted text-start">🏢 Department:</th>
<td class="fw-bold text-dark text-start">@Model.Department?.Name</td>
<th class="text-muted text-start">🗓️ Hire Date:</th>
<td class="fw-bold text-dark text-start">@Model.HireDate.ToString("MMMM dd, yyyy")</td>
<th class="text-muted text-start">🎂 Date of Birth:</th>
<td class="fw-bold text-dark text-start">@Model.DateOfBirth.ToString("MMMM dd, yyyy")</td>
<th class="text-muted text-start">👔 Employee Type:</th>
<td class="fw-bold text-dark text-start">@Model.EmployeeType?.Name</td>
<th class="text-muted text-start">⚧ Gender:</th>
<td class="fw-bold text-dark text-start">@Model.Gender</td>
<th class="text-muted text-start">💰 Salary:</th>
<td class="fw-bold text-dark text-start">$@Model.Salary.ToString("N2")</td>
<form asp-action="Delete" method="post" class="text-center">
<input type="hidden" asp-for="Id" />
<button type="submit" class="btn btn-danger btn-lg me-3">
<i class="bi bi-trash-fill"></i> Delete
<a asp-action="List" class="btn btn-secondary btn-lg">
<i class="bi bi-arrow-left-circle-fill"></i> Cancel
@model EmployeePortal.Models.Employee
@{
ViewData["Title"] = "Delete Employee";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-4 border rounded">
<div class="text-center mb-4">
<h2 class="text-danger mb-3"><i class="bi bi-exclamation-triangle-fill"></i> Confirm Delete</h2>
<p class="lead">Are you sure you want to delete the following employee?</p>
<h3 class="text-primary">@Model.FullName</h3>
</div>
<div class="table-responsive mb-4">
<table class="table table-borderless">
<tbody>
<tr>
<th class="text-muted text-start" style="width: 30%;">📧 Email:</th>
<td class="fw-bold text-dark text-start">@Model.Email</td>
</tr>
<tr>
<th class="text-muted text-start">💼 Designation:</th>
<td class="fw-bold text-dark text-start">@Model.Designation?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">🏢 Department:</th>
<td class="fw-bold text-dark text-start">@Model.Department?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">🗓️ Hire Date:</th>
<td class="fw-bold text-dark text-start">@Model.HireDate.ToString("MMMM dd, yyyy")</td>
</tr>
<tr>
<th class="text-muted text-start">🎂 Date of Birth:</th>
<td class="fw-bold text-dark text-start">@Model.DateOfBirth.ToString("MMMM dd, yyyy")</td>
</tr>
<tr>
<th class="text-muted text-start">👔 Employee Type:</th>
<td class="fw-bold text-dark text-start">@Model.EmployeeType?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">⚧ Gender:</th>
<td class="fw-bold text-dark text-start">@Model.Gender</td>
</tr>
<tr>
<th class="text-muted text-start">💰 Salary:</th>
<td class="fw-bold text-dark text-start">$@Model.Salary.ToString("N2")</td>
</tr>
</tbody>
</table>
</div>
<form asp-action="Delete" method="post" class="text-center">
<input type="hidden" asp-for="Id" />
<button type="submit" class="btn btn-danger btn-lg me-3">
<i class="bi bi-trash-fill"></i> Delete
</button>
<a asp-action="List" class="btn btn-secondary btn-lg">
<i class="bi bi-arrow-left-circle-fill"></i> Cancel
</a>
</form>
</div>
</div>
</div>
</div>
</div>
@model EmployeePortal.Models.Employee
@{
ViewData["Title"] = "Delete Employee";
}
<div class="container mt-1">
<div class="row justify-content-center">
<div class="col-lg-8 col-md-10">
<div class="card border-0 shadow-sm">
<div class="card-body p-4 border rounded">
<div class="text-center mb-4">
<h2 class="text-danger mb-3"><i class="bi bi-exclamation-triangle-fill"></i> Confirm Delete</h2>
<p class="lead">Are you sure you want to delete the following employee?</p>
<h3 class="text-primary">@Model.FullName</h3>
</div>
<div class="table-responsive mb-4">
<table class="table table-borderless">
<tbody>
<tr>
<th class="text-muted text-start" style="width: 30%;">📧 Email:</th>
<td class="fw-bold text-dark text-start">@Model.Email</td>
</tr>
<tr>
<th class="text-muted text-start">💼 Designation:</th>
<td class="fw-bold text-dark text-start">@Model.Designation?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">🏢 Department:</th>
<td class="fw-bold text-dark text-start">@Model.Department?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">🗓️ Hire Date:</th>
<td class="fw-bold text-dark text-start">@Model.HireDate.ToString("MMMM dd, yyyy")</td>
</tr>
<tr>
<th class="text-muted text-start">🎂 Date of Birth:</th>
<td class="fw-bold text-dark text-start">@Model.DateOfBirth.ToString("MMMM dd, yyyy")</td>
</tr>
<tr>
<th class="text-muted text-start">👔 Employee Type:</th>
<td class="fw-bold text-dark text-start">@Model.EmployeeType?.Name</td>
</tr>
<tr>
<th class="text-muted text-start">⚧ Gender:</th>
<td class="fw-bold text-dark text-start">@Model.Gender</td>
</tr>
<tr>
<th class="text-muted text-start">💰 Salary:</th>
<td class="fw-bold text-dark text-start">$@Model.Salary.ToString("N2")</td>
</tr>
</tbody>
</table>
</div>
<form asp-action="Delete" method="post" class="text-center">
<input type="hidden" asp-for="Id" />
<button type="submit" class="btn btn-danger btn-lg me-3">
<i class="bi bi-trash-fill"></i> Delete
</button>
<a asp-action="List" class="btn btn-secondary btn-lg">
<i class="bi bi-arrow-left-circle-fill"></i> Cancel
</a>
</form>
</div>
</div>
</div>
</div>
</div>
Modifying the Layout Page:
Finally, modify the _Layout.cshtml file as follows. The _Layout.cshtml view defines the main layout and structure shared by all pages in the application. It includes the header, navigation menu, footer, and references to CSS and JavaScript files. This layout ensures a consistent look and feels across every view, making navigation easy and giving a good user experience.
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - EmployeePortal</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/EmployeePortal.styles.css" asp-append-version="true" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.5.0/font/bootstrap-icons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />
<body class="d-flex flex-column min-vh-100">
<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #1e3a8a;">
<div class="container-fluid">
<a class="navbar-brand d-flex align-items-center fw-bold fs-4" asp-area="" asp-controller="Home" asp-action="Index" style="letter-spacing: 0.05em;">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent"
aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<a class="nav-link px-3 @((ViewContext.RouteData.Values["action"]?.ToString() == "Index") ? "active" : "")"
asp-area="" asp-controller="Home" asp-action="Index">Home</a>
<a class="nav-link px-3 @((ViewContext.RouteData.Values["controller"]?.ToString() == "Employee" && ViewContext.RouteData.Values["action"]?.ToString() == "List") ? "active" : "")"
asp-area="" asp-controller="Employee" asp-action="List">Employee List</a>
<a class="nav-link px-3 @((ViewContext.RouteData.Values["controller"]?.ToString() == "Employee" && ViewContext.RouteData.Values["action"]?.ToString() == "Create") ? "active" : "")"
asp-area="" asp-controller="Employee" asp-action="Create">Add Employee</a>
<ul class="navbar-nav ms-auto align-items-center">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" style="user-select:none;">
<img src="https://randomuser.me/api/portraits/men/75.jpg" alt="User Avatar" class="rounded-circle me-2" style="width:36px; height:36px; object-fit:cover; border: 2px solid #fff; box-shadow: 0 0 6px rgba(0,0,0,0.3);" />
<span class="d-none d-lg-inline text-white fw-semibold">Admin</span>
<ul class="dropdown-menu dropdown-menu-end shadow" aria-labelledby="userDropdown" style="min-width: 180px;">
<li><a class="dropdown-item" asp-area="" asp-controller="Account" asp-action="Profile">Profile</a></li>
<li><a class="dropdown-item" asp-area="" asp-controller="Account" asp-action="Settings">Settings</a></li>
<li><hr class="dropdown-divider" /></li>
<li><a class="dropdown-item text-danger" asp-area="" asp-controller="Account" asp-action="Logout">Logout</a></li>
<main role="main" class="flex-grow-1 container py-4">
<footer class="bg-dark text-light pt-5 pb-4 mt-auto">
<h5 class="text-primary fw-bold mb-3">EmployeePortal</h5>
<p>Manage your workforce with confidence and ease. EmployeePortal brings simplicity and power together.</p>
<small>© 2025 EmployeePortal. All rights reserved.</small>
<h6 class="fw-semibold mb-3 text-white">Quick Links</h6>
<ul class="list-unstyled">
<li><a href="/" class="text-decoration-none text-light">Home</a></li>
<li><a asp-area="" asp-controller="Employee" asp-action="List" class="text-decoration-none text-light">Employee List</a></li>
<li><a asp-area="" asp-controller="Employee" asp-action="Create" class="text-decoration-none text-light">Add Employee</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Privacy" class="text-decoration-none text-light">Privacy Policy</a></li>
<h6 class="fw-semibold mb-3 text-white">Contact Us</h6>
<address class="text-light">
1234 Corporate Blvd<br />
Cityname, State 56789<br />
Phone: <a href="tel:+1234567890" class="text-decoration-none text-light">+1 (234) 567-890</a><br />
Email: <a href="mailto:support@example.com" class="text-decoration-none text-light">support@employeeportal.com</a>
<a href="https://x.com/RoutPranaya" class="me-3 text-light" title="Twitter" target="_blank"><i class="bi bi-twitter fs-4"></i></a>
<a href="https://www.linkedin.com/in/pranaya-rout" class="me-3 text-light" title="LinkedIn" target="_blank"><i class="bi bi-linkedin fs-4"></i></a>
<a href="https://www.facebook.com/tutorialsdotnet/" class="me-3 text-light" title="Facebook" target="_blank"><i class="bi bi-facebook fs-4"></i></a>
<a href="https://t.me/dotnettutorials" class="me-3 text-light" title="Telegram" target="_blank"><i class="bi bi-telegram fs-4"></i></a>
<a href="https://wa.me/917021801173" class="me-3 text-light" title="WhatsApp" target="_blank"><i class="bi bi-whatsapp fs-4"></i></a>
<a href="https://www.youtube.com/%40DotNetTutorials" class="text-light" title="YouTube" target="_blank"><i class="bi bi-youtube fs-4"></i></a>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - EmployeePortal</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/EmployeePortal.styles.css" asp-append-version="true" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.5.0/font/bootstrap-icons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />
</head>
<body class="d-flex flex-column min-vh-100">
<header>
<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #1e3a8a;">
<div class="container-fluid">
<a class="navbar-brand d-flex align-items-center fw-bold fs-4" asp-area="" asp-controller="Home" asp-action="Index" style="letter-spacing: 0.05em;">
EmployeePortal
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent"
aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link px-3 @((ViewContext.RouteData.Values["action"]?.ToString() == "Index") ? "active" : "")"
asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link px-3 @((ViewContext.RouteData.Values["controller"]?.ToString() == "Employee" && ViewContext.RouteData.Values["action"]?.ToString() == "List") ? "active" : "")"
asp-area="" asp-controller="Employee" asp-action="List">Employee List</a>
</li>
<li class="nav-item">
<a class="nav-link px-3 @((ViewContext.RouteData.Values["controller"]?.ToString() == "Employee" && ViewContext.RouteData.Values["action"]?.ToString() == "Create") ? "active" : "")"
asp-area="" asp-controller="Employee" asp-action="Create">Add Employee</a>
</li>
</ul>
<ul class="navbar-nav ms-auto align-items-center">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" style="user-select:none;">
<img src="https://randomuser.me/api/portraits/men/75.jpg" alt="User Avatar" class="rounded-circle me-2" style="width:36px; height:36px; object-fit:cover; border: 2px solid #fff; box-shadow: 0 0 6px rgba(0,0,0,0.3);" />
<span class="d-none d-lg-inline text-white fw-semibold">Admin</span>
</a>
<ul class="dropdown-menu dropdown-menu-end shadow" aria-labelledby="userDropdown" style="min-width: 180px;">
<li><a class="dropdown-item" asp-area="" asp-controller="Account" asp-action="Profile">Profile</a></li>
<li><a class="dropdown-item" asp-area="" asp-controller="Account" asp-action="Settings">Settings</a></li>
<li><hr class="dropdown-divider" /></li>
<li><a class="dropdown-item text-danger" asp-area="" asp-controller="Account" asp-action="Logout">Logout</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="flex-grow-1 container py-4">
@RenderBody()
</main>
</div>
<footer class="bg-dark text-light pt-5 pb-4 mt-auto">
<div class="container">
<div class="row gy-4">
<div class="col-md-4">
<h5 class="text-primary fw-bold mb-3">EmployeePortal</h5>
<p>Manage your workforce with confidence and ease. EmployeePortal brings simplicity and power together.</p>
<small>© 2025 EmployeePortal. All rights reserved.</small>
</div>
<div class="col-md-4">
<h6 class="fw-semibold mb-3 text-white">Quick Links</h6>
<ul class="list-unstyled">
<li><a href="/" class="text-decoration-none text-light">Home</a></li>
<li><a asp-area="" asp-controller="Employee" asp-action="List" class="text-decoration-none text-light">Employee List</a></li>
<li><a asp-area="" asp-controller="Employee" asp-action="Create" class="text-decoration-none text-light">Add Employee</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Privacy" class="text-decoration-none text-light">Privacy Policy</a></li>
</ul>
</div>
<div class="col-md-4">
<h6 class="fw-semibold mb-3 text-white">Contact Us</h6>
<address class="text-light">
1234 Corporate Blvd<br />
Cityname, State 56789<br />
Phone: <a href="tel:+1234567890" class="text-decoration-none text-light">+1 (234) 567-890</a><br />
Email: <a href="mailto:support@example.com" class="text-decoration-none text-light">support@employeeportal.com</a>
</address>
<div>
<a href="https://x.com/RoutPranaya" class="me-3 text-light" title="Twitter" target="_blank"><i class="bi bi-twitter fs-4"></i></a>
<a href="https://www.linkedin.com/in/pranaya-rout" class="me-3 text-light" title="LinkedIn" target="_blank"><i class="bi bi-linkedin fs-4"></i></a>
<a href="https://www.facebook.com/tutorialsdotnet/" class="me-3 text-light" title="Facebook" target="_blank"><i class="bi bi-facebook fs-4"></i></a>
<a href="https://t.me/dotnettutorials" class="me-3 text-light" title="Telegram" target="_blank"><i class="bi bi-telegram fs-4"></i></a>
<a href="https://wa.me/917021801173" class="me-3 text-light" title="WhatsApp" target="_blank"><i class="bi bi-whatsapp fs-4"></i></a>
<a href="https://www.youtube.com/%40DotNetTutorials" class="text-light" title="YouTube" target="_blank"><i class="bi bi-youtube fs-4"></i></a>
</div>
</div>
</div>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - EmployeePortal</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/EmployeePortal.styles.css" asp-append-version="true" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.5.0/font/bootstrap-icons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />
</head>
<body class="d-flex flex-column min-vh-100">
<header>
<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #1e3a8a;">
<div class="container-fluid">
<a class="navbar-brand d-flex align-items-center fw-bold fs-4" asp-area="" asp-controller="Home" asp-action="Index" style="letter-spacing: 0.05em;">
EmployeePortal
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent"
aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link px-3 @((ViewContext.RouteData.Values["action"]?.ToString() == "Index") ? "active" : "")"
asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link px-3 @((ViewContext.RouteData.Values["controller"]?.ToString() == "Employee" && ViewContext.RouteData.Values["action"]?.ToString() == "List") ? "active" : "")"
asp-area="" asp-controller="Employee" asp-action="List">Employee List</a>
</li>
<li class="nav-item">
<a class="nav-link px-3 @((ViewContext.RouteData.Values["controller"]?.ToString() == "Employee" && ViewContext.RouteData.Values["action"]?.ToString() == "Create") ? "active" : "")"
asp-area="" asp-controller="Employee" asp-action="Create">Add Employee</a>
</li>
</ul>
<ul class="navbar-nav ms-auto align-items-center">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false" style="user-select:none;">
<img src="https://randomuser.me/api/portraits/men/75.jpg" alt="User Avatar" class="rounded-circle me-2" style="width:36px; height:36px; object-fit:cover; border: 2px solid #fff; box-shadow: 0 0 6px rgba(0,0,0,0.3);" />
<span class="d-none d-lg-inline text-white fw-semibold">Admin</span>
</a>
<ul class="dropdown-menu dropdown-menu-end shadow" aria-labelledby="userDropdown" style="min-width: 180px;">
<li><a class="dropdown-item" asp-area="" asp-controller="Account" asp-action="Profile">Profile</a></li>
<li><a class="dropdown-item" asp-area="" asp-controller="Account" asp-action="Settings">Settings</a></li>
<li><hr class="dropdown-divider" /></li>
<li><a class="dropdown-item text-danger" asp-area="" asp-controller="Account" asp-action="Logout">Logout</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="flex-grow-1 container py-4">
@RenderBody()
</main>
</div>
<footer class="bg-dark text-light pt-5 pb-4 mt-auto">
<div class="container">
<div class="row gy-4">
<div class="col-md-4">
<h5 class="text-primary fw-bold mb-3">EmployeePortal</h5>
<p>Manage your workforce with confidence and ease. EmployeePortal brings simplicity and power together.</p>
<small>© 2025 EmployeePortal. All rights reserved.</small>
</div>
<div class="col-md-4">
<h6 class="fw-semibold mb-3 text-white">Quick Links</h6>
<ul class="list-unstyled">
<li><a href="/" class="text-decoration-none text-light">Home</a></li>
<li><a asp-area="" asp-controller="Employee" asp-action="List" class="text-decoration-none text-light">Employee List</a></li>
<li><a asp-area="" asp-controller="Employee" asp-action="Create" class="text-decoration-none text-light">Add Employee</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Privacy" class="text-decoration-none text-light">Privacy Policy</a></li>
</ul>
</div>
<div class="col-md-4">
<h6 class="fw-semibold mb-3 text-white">Contact Us</h6>
<address class="text-light">
1234 Corporate Blvd<br />
Cityname, State 56789<br />
Phone: <a href="tel:+1234567890" class="text-decoration-none text-light">+1 (234) 567-890</a><br />
Email: <a href="mailto:support@example.com" class="text-decoration-none text-light">support@employeeportal.com</a>
</address>
<div>
<a href="https://x.com/RoutPranaya" class="me-3 text-light" title="Twitter" target="_blank"><i class="bi bi-twitter fs-4"></i></a>
<a href="https://www.linkedin.com/in/pranaya-rout" class="me-3 text-light" title="LinkedIn" target="_blank"><i class="bi bi-linkedin fs-4"></i></a>
<a href="https://www.facebook.com/tutorialsdotnet/" class="me-3 text-light" title="Facebook" target="_blank"><i class="bi bi-facebook fs-4"></i></a>
<a href="https://t.me/dotnettutorials" class="me-3 text-light" title="Telegram" target="_blank"><i class="bi bi-telegram fs-4"></i></a>
<a href="https://wa.me/917021801173" class="me-3 text-light" title="WhatsApp" target="_blank"><i class="bi bi-whatsapp fs-4"></i></a>
<a href="https://www.youtube.com/%40DotNetTutorials" class="text-light" title="YouTube" target="_blank"><i class="bi bi-youtube fs-4"></i></a>
</div>
</div>
</div>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
Modify Program Class:
Please modify the Program class as follows. This is the entry point of the ASP.NET Core application. It configures services like MVC, Entity Framework Core, and dependency injection for the EmployeeService. It also sets up middleware for handling requests, routing, and HTTPS redirection, and defines the default URL routing pattern.
using EmployeePortal.Data;
using EmployeePortal.Services;
using Microsoft.EntityFrameworkCore;
public static void Main(string[] args)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add ApplicationDbContext and configure SQL Server connection string
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("ECommerceDBConnection")));
builder.Services.AddScoped<EmployeeService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHttpsRedirection();
pattern: "{controller=Employee}/{action=List}/{id?}");
using EmployeePortal.Data;
using EmployeePortal.Services;
using Microsoft.EntityFrameworkCore;
namespace EmployeePortal
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add ApplicationDbContext and configure SQL Server connection string
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("ECommerceDBConnection")));
builder.Services.AddScoped<EmployeeService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Employee}/{action=List}/{id?}");
app.Run();
}
}
}
using EmployeePortal.Data;
using EmployeePortal.Services;
using Microsoft.EntityFrameworkCore;
namespace EmployeePortal
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add ApplicationDbContext and configure SQL Server connection string
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("ECommerceDBConnection")));
builder.Services.AddScoped<EmployeeService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Employee}/{action=List}/{id?}");
app.Run();
}
}
}
Applying EF Core Migrations and Database Creation
Run the following commands in the Package Manager Console:
- Add-Migration Mig1
- Update-Database

This will create the database with tables and seed the initial data. It should create the EmployeePortalDB database in SQL Server with the Employees table as shown in the image below.

That’s it. Now, run the application and test its functionalities; it should work as expected. We have successfully implemented the Employee Portal application, which allows administrators to perform various operations on Employee data.
In the next article, I will discuss the development of a Hospital Management Application using ASP.NET Core MVC and Entity Framework Core. I hope you enjoy this in-depth article on a Real-time Employee Portal Application using ASP.NET Core MVC. Please provide your valuable feedback on the Employee Portal Application using the ASP.NET Core MVC article, and let me know how we can improve this project.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.
I have read this article and create the same application in my local system. I have learnt many new concepts in it.
🎬 Watch Now: Learn how to build a complete Employee Portal using ASP.NET Core MVC!
This step-by-step tutorial video walks you through developing a powerful and user-friendly employee management system, from setting up the project to implementing all essential features like creating, updating, viewing, and deleting employee records.
Whether you’re a beginner or an experienced developer, this video will guide you through best practices and real-world coding examples to master ASP.NET Core MVC.
👉 Don’t miss out. Watch Now: https://www.youtube.com/watch?v=xtyuIYjNJD4 and start building your own Employee Portal today!