Index.cshtml.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using MediatR;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.AspNetCore.Mvc.RazorPages;
  4. using System.ComponentModel;
  5. using System.ComponentModel.DataAnnotations;
  6. namespace Admin.Pages.Director.Role
  7. {
  8. public class IndexModel(IMediator mediator) : PageModel
  9. {
  10. public int Total { get; set; } = 0;
  11. public List<GetRoles.Response> List { get; set; } = [];
  12. [Required]
  13. [DisplayName("역할(Role)")]
  14. [MaxLength(100)]
  15. [BindProperty]
  16. public string? RoleName { get; set; }
  17. public async Task OnGetAsync(CancellationToken ct)
  18. {
  19. List = await mediator.Send(new GetRoles.Query(), ct);
  20. Total = List.Count;
  21. }
  22. public async Task<IActionResult> OnPostAsync(CancellationToken ct)
  23. {
  24. try
  25. {
  26. if (!ModelState.IsValid)
  27. {
  28. throw new Exception("유효성 검사에 실패하였습니다.");
  29. }
  30. var command = new CreateRole.Command(
  31. RoleName: RoleName
  32. );
  33. await mediator.Send(command, ct);
  34. TempData["SuccessMessage"] = $"{RoleName} 역할이 추가되었습니다.";
  35. return RedirectToPage();
  36. }
  37. catch (Exception e)
  38. {
  39. TempData["ErrorMessages"] = e.Message;
  40. return Page();
  41. }
  42. }
  43. public async Task<IActionResult> OnPostDeleteAsync(string id, CancellationToken ct)
  44. {
  45. try
  46. {
  47. var role = await mediator.Send(new GetRole.Query(id), ct);
  48. if (role == null)
  49. {
  50. throw new Exception("존재하지 않는 역할(Role)입니다.");
  51. }
  52. await mediator.Send(new DeleteRole.Command(id), ct);
  53. TempData["SuccessMessage"] = $"{role.Name} 역할이 정상적으로 삭제되었습니다.";
  54. return RedirectToPage();
  55. }
  56. catch (Exception e)
  57. {
  58. TempData["ErrorMessages"] = e.Message;
  59. return RedirectToPage();
  60. }
  61. }
  62. }
  63. }