체크개발자's Blog

MVC - Paging (OrderBy -> Skip -> Take) 본문

프로그래밍/C# .NET

MVC - Paging (OrderBy -> Skip -> Take)

체크개발자 2021. 1. 30. 17:55

OrderBy -> Skip -> Take

 

 

 

Controller

 public ActionResult Index()
        {
            int maxListCount = 4;
            int pageNum = 1;

            if (Request.QueryString["page"] != null)
                pageNum = Convert.ToInt32(Request.QueryString["page"]);


            var books = db.Books.OrderBy(x => x.Book_U)
                .Skip(maxListCount * (pageNum-1)).Take(maxListCount).ToList();

            ViewBag.Page = pageNum;
            ViewBag.TotalCount = db.Books.Count();
            ViewBag.MaxListCount = maxListCount;

            return View(books);
        }

 

 

Index.cshtml

@{
    ViewBag.Title = "Index";
    int pageNum = ViewBag.Page ?? 1;
    int totalCount = ViewBag.TotalCount ?? 0;
    int maxListCount = ViewBag.MaxListCount ?? 1;
    int totalPageCount = Convert.ToInt32( Math.Ceiling((double)totalCount / maxListCount));@* 좀 더 효율적인 방법이 없을까? *@
}


<div class="text-center">
    <div class="btn-group">
        @for (int i = 1; i <= totalPageCount; i++)
        {
            <a class="btn btn-@(pageNum == i ? "primary":"default")" href="?page=@i">@i</a>
        }
        
        @* 주석 <a class="btn btn-@(pageNum == 1 ? "primary":"default")" href="?page=1">1</a>
        <a class="btn btn-@(pageNum == 2 ? "primary":"default")" href="?page=2">2</a>
        <a class="btn btn-@(pageNum == 3 ? "primary":"default")" href="?page=3">3</a>*@

    </div> 
</div>
Comments