Write.cshtml.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using SharedKernel.Extensions;
  2. using MediatR;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.RazorPages;
  5. using Microsoft.AspNetCore.Mvc.Rendering;
  6. using System.ComponentModel;
  7. using System.ComponentModel.DataAnnotations;
  8. namespace Admin.Pages.Forum.Posts.List
  9. {
  10. public class WriteModel(IMediator mediator) : PageModel
  11. {
  12. public string? ReturnUrl { get; set; }
  13. public List<SelectListItem> BoardList { get; set; } = [];
  14. [BindProperty]
  15. public InputModel Input { get; set; } = new();
  16. public sealed class InputModel
  17. {
  18. [DisplayName("게시판")]
  19. [Required(ErrorMessage = "{0}은 필수입니다.")]
  20. public int BoardID { get; set; }
  21. [DisplayName("제목")]
  22. [Required(ErrorMessage = "{0}은 필수입니다.")]
  23. [StringLength(255, ErrorMessage = "{0}은 {1}자 이내로 입력하세요.")]
  24. public string Subject { get; set; } = null!;
  25. [DisplayName("내용")]
  26. [StringLength(8000, ErrorMessage = "{0}은 {1}자 이내로 입력하세요.")]
  27. public string? Content { get; set; }
  28. [DisplayName("대표 이미지")]
  29. public IFormFile? ThumbnailFile { get; set; }
  30. [DisplayName("공지")]
  31. public bool IsNotice { get; set; } = false;
  32. [DisplayName("비밀")]
  33. public bool IsSecret { get; set; } = false;
  34. [DisplayName("익명")]
  35. public bool IsAnonymous { get; set; } = false;
  36. public string? ReturnUrl { get; set; }
  37. }
  38. public async Task OnGetAsync(CancellationToken ct)
  39. {
  40. var boards = await mediator.Send(new SearchBoards.Query(null, null, 1, 500), ct);
  41. BoardList = [..boards.List.Select(c => new SelectListItem
  42. {
  43. Value = c.ID.ToString(),
  44. Text = $"[{c.BoardGroupName}] {c.Name}"
  45. })];
  46. ReturnUrl = Request.Headers.Referer.ToString();
  47. }
  48. public async Task<IActionResult> OnPostAsync(CancellationToken ct)
  49. {
  50. try
  51. {
  52. if (!ModelState.IsValid)
  53. {
  54. throw new Exception(ModelState.GetErrorMessages());
  55. }
  56. await mediator.Send(new CreatePost.Command(
  57. Input.BoardID,
  58. Input.Subject,
  59. Input.Content,
  60. Input.ThumbnailFile,
  61. Input.IsNotice,
  62. Input.IsSecret,
  63. Input.IsAnonymous
  64. ), ct);
  65. TempData["SuccessMessage"] = "게시글이 등록되었습니다.";
  66. return RedirectToPage("/Forum/Posts/List/Index");
  67. }
  68. catch (Exception e)
  69. {
  70. TempData["ErrorMessages"] = e.Message;
  71. return RedirectToPage("/Forum/Posts/List/Write");
  72. }
  73. }
  74. }
  75. }