Pagination For Search Results ASP.NET MVC 5

Tiếp tục với bài trước, trong bài hôm này mình chia sẻ cách tìm kiếm dữ liệu trả về rồi phân trang(pagination) trong ASP.NET MVC 5. Mình viết tiếp code của bài trước bạn xem tại đây

Thật sự thì có plugin hổ trợ phân trang, nhưng mình thì không dùng. Hôm này mình sẽ lên một công thức tính toán để ta có thể phân trang tùy thích
Nếu bạn có xem bài trước rồi thì giờ bạn chỉ cần mở file PostController.cs lên và chỉnh sửa lại hàm index() như sau:


        public int pageSize = 2;
        public ActionResult Index(string txtSearch,int? page)
        {
       
            var data = (from s in _db.Posts select s);
            if (!String.IsNullOrEmpty(txtSearch))
            {
                ViewBag.txtSearch = txtSearch;
                data = data.Where(s => s.Title.Contains(txtSearch));
            }

            if (page > 0)
            {
                page = page;
            }
            else
            {
                page = 1;
            }
            int start = (int)(page - 1) * pageSize;
            
            ViewBag.pageCurrent = page;
            int totalPage = data.Count();
            float totalNumsize = (totalPage / (float)pageSize);
            int numSize = (int)Math.Ceiling(totalNumsize);
            ViewBag.numSize = numSize;
            ViewBag.posts = data.OrderByDescending(x => x.Id).Skip(start).Take(pageSize);
            return View();
        }

Đầu tiên mình cài đặt các tham số như sau:

  • pageSize: là số bài post mà mình cần hiển thị ra ngoài
  • ViewBag.pageCurrent: nhận giá trị page hiện tại
  • totalPage: tổng của tất cả dữ liệu bài
  • totalNumsize: tổng số trang cần hiển thị
  • Math.Ceiling: hàm dùng làm tròn số thập phân

Tiếp tục mình chỉnh sửa lại giao diện hiển thị , ta mở file Index.cshtml trong Views/Post/Index.cshtml 

@model MVC5_HelloWorld.Models.Post
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card">
                
                <div class="card-header">
                    List Posts
                    <a href="@Url.Action("Store", "Post")" class="btn btn-success">Add</a>
                </div>
                <div class="card-body">
                    <div class="card-header">
                        Search
                        @using (Html.BeginForm("Index", "Post", FormMethod.Get))
                        {
                            <input type="text" name="txtSearch" placeholder="Search!"/>
                            <button type="submit" class="btn btn-warning">Search</button>
                        }
                    </div>
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>STT</th>
                                <th>Title</th>
                                <th>Body</th>
                                <th>Created_at</th>
                                <th>Updated_at</th>
                                <th>Edit</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody>
                            @{
                                int i = 1;
                              
                            }
                            @foreach (var post in ViewBag.Posts)
                            {

                                <tr>
                                    <td>@i</td>
                                    <td>@post.Title</td>
                                    <td>@post.Body</td>
                                    <td>@post.Created_at</td>
                                    <td>@post.Updated_at</td>
                                    <td><a href="@Url.Action("Edit","Post",new {id=post.Id})" class="badge badge-warning">Modify</a></td>
                                    <td><a href="@Url.Action("Delete","Post",new {id=post.Id})" class="badge badge-danger">Remove</a></td>
                                </tr>
                                i++;
                            }
                        </tbody>
                       
                    </table>
                    <div class="card-footer">
                        <nav aria-label="Page navigation example">
                            <ul class="pagination">

                                @{
                                    int position;
                                    int pageCurrent = ViewBag.pageCurrent;
                                    string txtSearch = ViewBag.txtSearch;
                                    float numSize = ViewBag.numSize;
                                    if (pageCurrent > 1)
                                    {
                                        <li class="page-item">
                                            <a class="page-link" href="@Url.Action("Index", "Post", new { txtSearch = (txtSearch != "" ? txtSearch : null), page = pageCurrent-1 })" tabindex="-1">Previous</a>
                                        </li>
                                    }

                                    for (position = 1; position <= numSize; position++)
                                    {

                                        if (position == pageCurrent)
                                        {
                                            <li class="page-item active"><a class="page-link" href="@Url.Action("Index", "Post", new { txtSearch = (txtSearch != "" ? txtSearch : null), page = position })">@position</a></li>
                                        }

                                        else
                                        {
                                            <li class="page-item"><a class="page-link" href="@Url.Action("Index", "Post", new { txtSearch = (txtSearch != "" ? txtSearch : null), page = position })">@position</a></li>
                                        }

                                    }
                                    if (pageCurrent > 0 && pageCurrent < numSize)
                                    {
                                        <li class="page-item">
                                            <a class="page-link" href="@Url.Action("Index", "Post", new { txtSearch = (txtSearch != "" ? txtSearch : null), page = pageCurrent+1 })" tabindex="-1">Next</a>
                                        </li>
                                    }

                                }

                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Trong đoạn code bên trên cũng khá đơn giản, vì mình chỉ việc lập các numSize ra thôi
Demo:

Pagination For Search Results ASP.NET MVC 5Pagination For Search Results ASP.NET MVC 5

Ok vậy là xong! ::)

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)