Edit.cshtml.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using SharedKernel.Extensions;
  2. using MediatR;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.RazorPages;
  5. using System.ComponentModel.DataAnnotations;
  6. namespace Admin.Pages.Crypto.News
  7. {
  8. public class EditModel(IMediator mediator) : PageModel
  9. {
  10. public int SourceID { get; private set; }
  11. [BindProperty]
  12. public InputModel Input { get; set; } = new();
  13. public sealed class InputModel
  14. {
  15. [Required(ErrorMessage = "이름은 필수입니다.")]
  16. [StringLength(200, ErrorMessage = "이름은 {1}자 이하로 입력하세요.")]
  17. public string Name { get; set; } = null!;
  18. [Required(ErrorMessage = "URL은 필수입니다.")]
  19. [StringLength(2048, ErrorMessage = "URL은 {1}자 이하로 입력하세요.")]
  20. [DataType(DataType.Url)]
  21. public string Url { get; set; } = null!;
  22. [StringLength(500, ErrorMessage = "설명은 {1}자 이하로 입력하세요.")]
  23. public string? Description { get; set; }
  24. [Range(1, 1440, ErrorMessage = "수집주기는 1~1440분 사이로 입력하세요.")]
  25. public int IntervalMinutes { get; set; } = 10;
  26. public bool IsActive { get; set; } = true;
  27. }
  28. public async Task<IActionResult> OnGetAsync(int id, CancellationToken ct)
  29. {
  30. try
  31. {
  32. var source = await mediator.Send(new GetNewsSource.Query(id), ct);
  33. SourceID = source.ID;
  34. Input = new InputModel
  35. {
  36. Name = source.Name,
  37. Url = source.Url,
  38. Description = source.Description,
  39. IntervalMinutes = source.IntervalMinutes,
  40. IsActive = source.IsActive
  41. };
  42. return Page();
  43. }
  44. catch (KeyNotFoundException)
  45. {
  46. return NotFound();
  47. }
  48. }
  49. public async Task<IActionResult> OnPostAsync(int id, CancellationToken ct)
  50. {
  51. try
  52. {
  53. if (!ModelState.IsValid)
  54. {
  55. throw new Exception(ModelState.GetErrorMessages());
  56. }
  57. await mediator.Send(new UpdateNewsSource.Command(
  58. id,
  59. Input.Name,
  60. Input.Url,
  61. Input.Description,
  62. Input.IntervalMinutes,
  63. Input.IsActive
  64. ), ct);
  65. TempData["SuccessMessage"] = $"{Input.Name} 소스가 수정되었습니다.";
  66. return RedirectToPage("/Crypto/News/Edit", new { id });
  67. }
  68. catch (Exception e)
  69. {
  70. TempData["ErrorMessages"] = e.Message;
  71. return RedirectToPage("/Crypto/News/Edit", new { id });
  72. }
  73. }
  74. }
  75. }