0% found this document useful (0 votes)
8 views4 pages

Employee Controller

The document outlines an EmployeeController class in an ASP.NET Core application, which manages employee-related actions such as creating, editing, and deleting employees. It utilizes dependency injection for accessing the unit of work and applies authorization policies to restrict access to certain actions. The controller handles both GET and POST requests, includes error handling, and employs validation for employee data before performing database operations.

Uploaded by

devfeuze132
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Employee Controller

The document outlines an EmployeeController class in an ASP.NET Core application, which manages employee-related actions such as creating, editing, and deleting employees. It utilizes dependency injection for accessing the unit of work and applies authorization policies to restrict access to certain actions. The controller handles both GET and POST requests, includes error handling, and employs validation for employee data before performing database operations.

Uploaded by

devfeuze132
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

using Microsoft.AspNetCore.

Authorization;
using Microsoft.AspNetCore.Mvc;
using Multinet.Core.Entities;
using Multinet.Core.Validators;
using Multinet.Infrastructure.Interfaces;
using Multinet.Infrastructure.Statics;

namespace Multinet.UI.Controllers
{
[Authorize]
public class EmployeeController : Controller
{
#region Constructor
private readonly IUnitOfWork _unitOfWork;

public EmployeeController(IUnitOfWork unitOfWork)


{
_unitOfWork = unitOfWork;
}
#endregion

#region Index
[Authorize(Policy = "AccidentsPolicy")]
public async Task<IActionResult> Index()
{
try
{
var employees = await
_unitOfWork.EmployeeRepository.GetAllEmployees();

return View(employees);
}
catch (Exception ex)
{
TempData["errorMessage"] = ex.Message;
return View();
}
}
#endregion

#region Create GET


[HttpGet]
[Authorize(Policy = "AccidentsPolicy")]
public async Task<IActionResult> Create()
{
ViewBag.Departments = await
_unitOfWork.DepartmentRepository.GetAllDepartments();

return View(new Employee());


}
#endregion

#region Create POST


[HttpPost]
[AutoValidateAntiforgeryToken]
[Authorize(Policy = "AccidentsPolicy")]
public async Task<IActionResult> Create(Employee employee)
{
try
{
employee.Matricule = StaticMethod.GenerateMatricule(); // Utiliser
la méthode statique

EmployeeValidator validationResult = new EmployeeValidator();

var employeeState = validationResult.Validate(employee);

if (!employeeState.IsValid)
{
ViewBag.Departments = await
_unitOfWork.DepartmentRepository.GetAllDepartments();
return Json(new { success = false, message = string.Join(", ",
employeeState.Errors.Select(e => e.ErrorMessage))});
}
else
{
if (ModelState.IsValid)
{

var employeeVM = new Employee


{
Matricule = employee.Matricule,
Name = employee.Name,
Email = employee.Email,
Fonction = employee.Fonction,
Contact = employee.Contact,
DepartmentId = employee.DepartmentId
};

await
_unitOfWork.EmployeeRepository.AddEmployee(employeeVM);
await _unitOfWork.SaveAsync();

return Json(new { success = true, message = "Employé ajouté


avec succès", url = Url.Action("Index") });
}

ViewBag.Departments = await
_unitOfWork.DepartmentRepository.GetAllDepartments();
return Json(new { success = false, message = "État du modèle
invalide"});
}
}
catch (Exception ex)
{
ViewBag.Departments = await
_unitOfWork.DepartmentRepository.GetAllDepartments();
return Json(new { success = false, message = ex.Message});
}
}
#endregion

#region Edit GET


[HttpGet]
[Authorize(Policy = "AccidentsPolicy")]
public async Task<IActionResult> Edit(int id)
{
try
{
var employee = await
_unitOfWork.EmployeeRepository.GetEmployeeById(id);
if (employee == null)
{
TempData["errorMessage"] = "Entity Employee is empty";
return RedirectToAction("Index");
}

ViewBag.Departments = await
_unitOfWork.DepartmentRepository.GetAllDepartments();
return View(employee);
}
catch (Exception ex)
{
TempData["errorMessage"] = ex.Message;
return RedirectToAction("Index");
}
}
#endregion

#region Edit POST


[HttpPost]
[AutoValidateAntiforgeryToken]
[Authorize(Policy = "AccidentsPolicy")]
public async Task<IActionResult> Edit(Employee employee)
{
try
{
EmployeeValidator validationResult = new EmployeeValidator();

var employeeState = validationResult.Validate(employee);

if (!employeeState.IsValid)
{
ViewBag.Departments = await
_unitOfWork.DepartmentRepository.GetAllDepartments();
return Json(new { success = false, message = string.Join(", ",
employeeState.Errors.Select(e => e.ErrorMessage))});
}
else
{
if (ModelState.IsValid)
{
await
_unitOfWork.EmployeeRepository.UpdateEmployee(employee);
await _unitOfWork.SaveAsync();

return Json(new { success = true, message = "Employé


modifié avec succès", url = Url.Action("Index") });
}

ViewBag.Departments = await
_unitOfWork.DepartmentRepository.GetAllDepartments();
return Json(new { success = false, message = "État du modèle
invalide"});
}
}
catch (Exception ex)
{
ViewBag.Departments = await
_unitOfWork.DepartmentRepository.GetAllDepartments();
return Json(new { success = false, message = ex.Message});
}
}
#endregion

#region Delete
[HttpPost]
[Route("Employee/Delete/{id}")]
[Authorize(Policy = "LockDeletePolicy")]
public async Task<IActionResult> Delete(int id)
{
try
{
if (ModelState.IsValid)
{
await _unitOfWork.EmployeeRepository.DeleteEmployee(id);
await _unitOfWork.SaveAsync();

TempData["successMessage"] = "Employé supprimé avec succès";


return RedirectToAction("Index");
}

TempData["errorMessage"] = "État du modèle invalide";


return RedirectToAction("Index");
}
catch (Exception ex)
{
TempData["errorMessage"] = ex.Message;
return RedirectToAction("Index");
}
}
#endregion
}
}

You might also like