0

I am struggling with dotnet core for implement pagenation But I dont know how.

Plese help me guys.

How can I do connect my <script function> in index.cshtml for to receive data from Controller file.

this is my Notice Model

using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Build.Execution;
using System.ComponentModel.DataAnnotations;

namespace Board.Models
{
    public class Notice
    {
        public int Id { get; set; }
        public int Views_Number { get; set; }
        public string Title { get; set; }

        public string Content { get; set; }

        public string UserName { get; set; }

        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime UpdateDate { get; set; }
        
        public string Category { get; set; }

        public string? fileAttachMent { get; set; }

        public string? FileName { get; set; }

        public byte[]? fileContents { get; set; }


    }
}

and this is my index code part of Controller

// GET: Notices
        [ActionName("Index")]
        public async Task<IActionResult> Index(string? Category, string? searchString)
        {

            //LINQ to get list of category
            IQueryable<string> categoryQuery = from m in _context.Notice
                                               orderby m.UpdateDate descending
                                               select m.Category;

            var notice = from m in _context.Notice select m;
            notice = from m in _context.Notice orderby m.UpdateDate descending select m;

            if (!string.IsNullOrEmpty(searchString)) {

                notice = notice.Where(x => x.Title!.Contains(searchString)); 
            }

            if (!string.IsNullOrEmpty(Category))
            {
               
                notice = notice.Where(x => x.Category == Category);
              
            }

            var noticeCategory = new NoticeCategory
            {
                Categorys = new SelectList(await categoryQuery.Distinct().ToListAsync()),
                Notices = await notice.ToListAsync()
                
            };
           
            //var notice_list = Enumerable.Reverse(_context.Notice).ToList();

            return View(noticeCategory);
        }

last my index.cshtml code

@model Board.Models.NoticeCategory


@{
    ViewData["Title"] = "Index";
}

@section Scripts{
    <script>
        function ChangeSelete() {
            var optionSeleted = document.getElementById('selected');
            var selected = optionSeleted.options[optionSeleted.selectedIndex].value;
            console.log(selected)
            window.location.href = "/Notices/Index/?Category=" + selected;
        }
    //pagenation
        let totalData ; //총 데이터 수
        let dataPerPage //한 페이지에 나타낼 글 수
        let pageCount = 10; //페이징에 나타낼 페이지 수
        let globalCurrentPage = 1; //현재 페이지
        let dataList; //표시하려하는 데이터 리스트

        $(document).ready(function () {
            //글 목록 표시 호출 (테이블 생성)
            dataPerPage = $("#dataPerPage").val();
            displayData(1, dataPerPage);

            totalData = "@Model.Notices.Count"
            dataList = "@Model.Notices"

            console.log("실행되냐???")
            //페이징 표시 호출
            paging(totalData, dataPerPage, pageCount, 1);
        });

        function displayData(currentPage, dataPerPage) {

            let chartHtml = "";

            //Number로 변환하지 않으면 아래에서 +를 할 경우 스트링 결합이 되어버림..
            currentPage = Number(currentPage);
            dataPerPage = Number(dataPerPage);

            for (
                var i = (currentPage - 1) * dataPerPage;
                i < (currentPage - 1) * dataPerPage + dataPerPage;
                i++
            ) {
                chartHtml +=
                    "<tr><td>" +
                    dataList[i].d1 +
                    "</td><td>" +
                    dataList[i].d2 +
                    "</td><td>" +
                    dataList[i].d3 +
                    "</td></tr>";
            } //dataList는 임의의 데이터임.. 각 소스에 맞게 변수를 넣어주면 됨...
            $("#dataTableBody").html(chartHtml);
        }

        function paging(totalData, dataPerPage, pageCount, currentPage) {
            console.log("currentPage : " + currentPage);

            totalPage = Math.ceil(totalData / dataPerPage); //총 페이지 수

            if (totalPage < pageCount) {
                pageCount = totalPage;
            }

            let pageGroup = Math.ceil(currentPage / pageCount); // 페이지 그룹
            let last = pageGroup * pageCount; //화면에 보여질 마지막 페이지 번호

            if (last > totalPage) {
                last = totalPage;
            }

            let first = last - (pageCount - 1); //화면에 보여질 첫번째 페이지 번호
            let next = last + 1;
            let prev = first - 1;

            let pageHtml = "";

            if (prev > 0) {
                pageHtml += "<li><a href='#' id='prev'> 이전 </a></li>";
            }

            //페이징 번호 표시
            for (var i = first; i <= last; i++) {
                if (currentPage == i) {
                    pageHtml +=
                        "<li class='on'><a href='#' id='" + i + "'>" + i + "</a></li>";
                } else {
                    pageHtml += "<li><a href='#' id='" + i + "'>" + i + "</a></li>";
                }
            }

            if (last < totalPage) {
                pageHtml += "<li><a href='#' id='next'> 다음 </a></li>";
            }

            $("#pagingul").html(pageHtml);
            let displayCount = "";
            displayCount = "현재 1 - " + totalPage + " 페이지 / " + totalData + "건";
            $("#displayCount").text(displayCount);


            //페이징 번호 클릭 이벤트
            $("#pagingul li a").click(function () {
                let $id = $(this).attr("id");
                selectedPage = $(this).text();

                if ($id == "next") selectedPage = next;
                if ($id == "prev") selectedPage = prev;

                //전역변수에 선택한 페이지 번호를 담는다...
                globalCurrentPage = selectedPage;
                //페이징 표시 재호출
                paging(totalData, dataPerPage, pageCount, selectedPage);
                //글 목록 표시 재호출
                displayData(selectedPage, dataPerPage);
            });
        }
        $("#dataPerPage").change(function () {
            dataPerPage = $("#dataPerPage").val();
            //전역 변수에 담긴 globalCurrent 값을 이용하여 페이지 이동없이 글 표시개수 변경
            paging(totalData, dataPerPage, pageCount, globalCurrentPage);
            displayData(globalCurrentPage, dataPerPage);
        });
    </script>
}
<style>
    ul {
        text-align: center;
        display: inline-block;
        border: 1px solid #ccc;
        border-right: 0;
        padding-left: 0;
    }

        ul li {
            text-align: center;
            float: left;
            list-style: none;
        }

            ul li a {
                display: block;
                font-size: 14px;
                color: black;
                padding: 9px 12px;
                border-right: solid 1px #ccc;
                box-sizing: border-box;
                text-decoration-line: none;
            }

            ul li.on {
                background: #eda712;
            }

                ul li.on a {
                    color: #fff;
                }
</style>


@*
asp-items="Model.Categorys"*@

<div style="width:500px; height:50px; margin-top:40px; display: flex;">
    <div style="padding-right:10px;">
        <select asp-for="Category" asp-items="Model.Categorys" id="selected" onchange="ChangeSelete()" class="form-select" aria-label="Default select example">
            <option value="">All</option>
            @*<option value="무료나눔"></option>
            <option value="정보">정보</option>
            <option value="잡담">잡담</option>*@
        </select>
    </div>
    <div>
        
    </div>
    <div>
        <form asp-controller="Notices" asp-action="Index" method="get">
            <p>
                Title: <input type="text" name="SearchString" />
                <input type="submit" value="Filter" />
            </p>
        </form>
    </div>
</div>


<div>
    <span id="displayCount"></span>
        <table class="table table-striped table-hover">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Notices![0].Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Notices![0].Category)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Notices![0].Title)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Notices![0].UserName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Notices![0].UpdateDate)
                </th>
                <th>
                    조회수
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Notices!)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category)
                    </td>
                    <td>
                        <a asp-action="Details" asp-route-id="@item.Id">@Html.DisplayFor(modelItem => item.Title)</a>
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.UserName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.UpdateDate)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Views_Number)
                        @* <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>*@
                    </td>

                </tr>
            }

    </table>
</div>
<div>
    <!-- pagination -->
    <ul id="pagingul">
    </ul>
</div>
<p>
    <a asp-action="Create"><button type="button" class="btn btn-outline-secondary">글쓰기</button></a>
</p>

I am struggling with dotnet core for implement pagenation But I dont know how.

Plese help me guys.

How can I do connect my <script function> in index.cshtml for to receive data from Controller file.

Yi won
  • 3
  • 2
  • In your controller, you can get one page of data by using [`Skip()` and `Take()`](https://stackoverflow.com/questions/15385905/linq-with-skip-and-take) – Hans Kesting Mar 23 '23 at 12:03

0 Answers0