Pagination.cs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using Microsoft.AspNetCore.WebUtilities;
  2. using System.Reflection;
  3. namespace economy.Models
  4. {
  5. public class Pagination
  6. {
  7. public int Page { get; set; } = 0; // 현재 페이지
  8. public int TotalRows { get; set; } = 0; // 전체 항목 수
  9. public int TotalPage { get; set; } = 0; // 전체 페이지 수
  10. public int PerPage = 10;
  11. public int StartPage = 0; // 현재 페이지의 시작 번호
  12. public int EndPage = 0; // 현재 페이지의 마지막 번호
  13. public int PageGroupSize = 10; // 한번에 보여줄 페이지 번호 개수
  14. public int CurrentPageGroup = 0; // 현재 페이지가 속한 페이지 그룹의 시작번호
  15. public int GroupStartPage = 0; // 페이지 그룹의 시작 페이지 번호
  16. public int GroupEndPage = 0; // 페이지 그룹의 마지막 페이지 번호
  17. public int PrevGroupPage = 0; // 이전 페이지 그룹의 페이지 번호
  18. public int NextGroupPage = 0; // 다음 페이지 그룹 페이지 번호
  19. private Dictionary<string, string> QueryStringParams;
  20. public Pagination(int? totalRows, int page, int perPage, object? queryParams)
  21. {
  22. Page = page;
  23. PerPage = perPage;
  24. TotalRows = (totalRows ?? 0);
  25. TotalPage = ((int)Math.Ceiling((double)TotalRows / perPage));
  26. CurrentPageGroup = (int)Math.Ceiling((double)Page / PageGroupSize);
  27. StartPage = ((CurrentPageGroup - 1) * PageGroupSize + 1);
  28. EndPage = Math.Min((StartPage + PageGroupSize - 1), TotalPage);
  29. GroupStartPage = (GroupStartPage - PageGroupSize);
  30. GroupEndPage = (((Page - 1) / PageGroupSize + 1) * PageGroupSize);
  31. PrevGroupPage = Math.Max(StartPage - PageGroupSize, 1); // 이전 페이지 그룹의 첫 페이지 계산
  32. NextGroupPage = Math.Min(EndPage + 1, TotalPage); // 다음 페이지 그룹의 첫 페이지 계산
  33. // 객체를 쿼리스트링으로 변환
  34. QueryStringParams = ToDictionary(queryParams);
  35. }
  36. // 이전 페이지 여부
  37. public bool HasPreviousPage => (Page > 1);
  38. // 다음 페이지 여부
  39. public bool HasNextPage => (Page < TotalPage);
  40. // 객체를 Dictionary로 변환하는 메서드
  41. private Dictionary<string, string> ToDictionary(object? obj)
  42. {
  43. var dictionary = new Dictionary<string, string>();
  44. if (obj is null) {
  45. return dictionary;
  46. }
  47. var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  48. foreach (var prop in properties)
  49. {
  50. var value = prop.GetValue(obj)?.ToString();
  51. if (!string.IsNullOrEmpty(value))
  52. {
  53. dictionary.Add(prop.Name, value);
  54. }
  55. }
  56. return dictionary;
  57. }
  58. // 최종 쿼리스트링을 반환하는 메서드
  59. public string BuildQueryString()
  60. {
  61. if (QueryStringParams == null || QueryStringParams.Count == 0)
  62. {
  63. return "";
  64. }
  65. // 쿼리스트링이 있을 경우, AddQueryString으로 변환 후 ? 제거
  66. return "&" + QueryHelpers.AddQueryString("", QueryStringParams).TrimStart('?');
  67. }
  68. }
  69. }