DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

ASP.NET MVC 5 Ajax Pagination For Search Results

Continue with the previous article, today I will share way pagination use AJAX in ASP.NET MVC 5. the previous article , we have building pagination simple example, you can see again

In the article, i use code the code of the previous post
you open HomeController.cs fil in Controller folder and pass the following code below to it

public ActionResult Lists()
        {
            return View();
        }

        [HttpGet]
        public JsonResult getAllPost(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;
            var dataPost = data.OrderByDescending(x => x.Id).Skip(start).Take(pageSize);
            List<Post> listPost = new List<Post>();
            listPost = dataPost.ToList();
            // return Json(listPost);
            return Json(new { data = listPost,pageCurrent = page,numSize=numSize }, JsonRequestBehavior.AllowGet);
        }
Enter fullscreen mode Exit fullscreen mode
  • getAllPost(): I get all the data in Post table, after then return type Json
  • List():use display template, so you can create Lists.cshtml in Views/Post/Lists.cshtml directory

Okay, you open Lists.cshtml file and edit the interface

@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
                         <input type="text" name="txtSearch" placeholder="Search!" class="txtSearch"/>
                         <button type="button" class="btn btn-warning"  id="search">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 class="load-list">

                        </tbody>

                    </table>
                    <div class="card-footer">
                        <nav aria-label="Page navigation example">
                            <ul class="pagination" id="load-pagination">


                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Note: class="load-list" and id="load-pagination", i use display the data and list pagination display

$(document).ready(function () {

            //function load pagination
            var load = function (txtSearch, page) {
                $.ajax({
                    url: '@Url.Action("getAllPost","Post")',
                    type: "GET",
                    data: { txtSearch:txtSearch , page: page },
                    dataType: 'json',
                    contentType: 'application/json;charset=utf-8',
                    success: function (result) {
                        console.log(result);
                        var str = "";
                        $.each(result.data, function (index, value) {

                            //convert date to string
                            var dateCreated = value.Created_at;
                            var dateCreated_string = new Date(parseInt(dateCreated.replace("/Date(", "").replace(")/", ""), 10));
                            var created_at = dateCreated_string.getFullYear() + "/" + dateCreated_string.getMonth() + "/" + dateCreated_string.getDate();

                            var dateUpdated = value.Updated_at;
                            var dateUpdated_string = new Date(parseInt(dateUpdated.replace("/Date(", "").replace(")/", ""), 10));
                            var Updated_at = dateUpdated_string.getFullYear() + "/" + dateUpdated_string.getMonth() + "/" + dateUpdated_string.getDate();
                            //

                            //create list post
                            var dateUpdated = new Date(value.Updated_at);
                            str += "<tr>";
                               str += "<td>"+(value.Id)+"</td>";
                                str += "<td>"+value.Title + "</td>";
                                str += "<td>" + value.Body + "</td>";
                                str += "<td>" + created_at+ "</td>";
                                str += "<td>"+ Updated_at + "</td>";
                                str += "<td><a href='/Post/Edit/"+value.id+"' class='badge badge-warning'>Modify</a></td>";
                                str += "<td><a href='/Post/Delete/"+value.id+"' class='badge badge-danger'>Delete</a></td>";
                            str += "</tr>";

                            //create pagination
                            var pagination_string = "";
                            var pageCurrent = result.pageCurrent;
                            var numSize = result.numSize;

                            //create button previous
                            if (pageCurrent > 1) {
                                var pagePrevious = pageCurrent - 1;
                                pagination_string += '<li class="page-item"><a href="" class="page-link" data-page=' + pagePrevious + '>Previous</a></li>';
                            }

                            for (i = 1; i <= numSize; i++){
                                if (i == pageCurrent) {
                                    pagination_string += '<li class="page-item active"><a href="" class="page-link" data-page=' + i + '>'+pageCurrent+'</a></li>';
                                } else {
                                    pagination_string += '<li class="page-item"><a href="" class="page-link" data-page=' + i + '>'+i+'</a></li>';
                                }
                             }

                             //create button next
                             if (pageCurrent > 0 && pageCurrent < numSize) {
                                var pageNext = pageCurrent + 1;
                                pagination_string += '<li class="page-item"><a href="" class="page-link"  data-page=' + pageNext + '>Next</a></li>';
                             }

                        //load pagination
                        $("#load-pagination").html(pagination_string);
                     });

                        //load str to class="load-list"
                        $(".load-list").html(str);
                    }
                });
            }

   //load init
   load(null, 1);
});

Enter fullscreen mode Exit fullscreen mode

The code above, i have handle load pagination, you can insert two params(txtSearch,page), default page=1, txtSearch=null
url: '@ Url.Action ("getAllPost", "Post")': URL:/Post/GetAllPost in class HomeController.cs
Okay, you see in the code above, we use page number pagination insert , after then, using ajax get value it

We will build function click pagination

//click event pagination 
           $("body").on("click",".pagination li a",function (event) {
               event.preventDefault();
               var page = $(this).attr('data-page');

               //load event pagination
               var txtSearch = $(".txtSearch").val();
               if (txtSearch != "") {
                   load(txtSearch, page)
               }
               else {
                   load(null, page);
               }

           });
Enter fullscreen mode Exit fullscreen mode

Continue, function click search

//click event search
            $("#search").click(function () {
                var txtSearch = $(".txtSearch").val();
                if (txtSearch != "") {
                    load(txtSearch, 1)
                }
                else {
                    load(null, 1);
                }

            });
Enter fullscreen mode Exit fullscreen mode

Demo:
ASP.NET MVC 5 Ajax Pagination For Search Results - hoanguyenit.com

ASP.NET MVC 5 Ajax Pagination For Search Results - hoanguyenit.com

Post: ASP.NET MVC 5 Ajax Pagination For Search Results

Top comments (0)