Pagination.cs 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using Microsoft.AspNetCore.WebUtilities;
  2. using System.Reflection;
  3. namespace bitforum.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. {
  46. return dictionary;
  47. }
  48. var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  49. foreach (var prop in properties)
  50. {
  51. var value = prop.GetValue(obj)?.ToString();
  52. if (!string.IsNullOrEmpty(value))
  53. {
  54. dictionary.Add(prop.Name, value);
  55. }
  56. }
  57. return dictionary;
  58. }
  59. // 최종 쿼리스트링을 반환하는 메서드
  60. public string BuildQueryString()
  61. {
  62. if (QueryStringParams == null || QueryStringParams.Count == 0)
  63. {
  64. return "";
  65. }
  66. // 쿼리스트링이 있을 경우, AddQueryString으로 변환 후 ? 제거
  67. return "&" + QueryHelpers.AddQueryString("", QueryStringParams).TrimStart('?');
  68. }
  69. }
  70. }