Pagination Using JavaScript In MVC

In this article, I will show, how to make pagination with the retrieved data, using jQuery in MVC.

  1. Open Visual Studio. Select New Project.
  2. In Visual C# tab, select ASP.NET Web Application.
  3. Now, select an Empty Project. In "Add folders and core reference for:" section, select MVC. Select OK.
  4. Now, right click on your solution and another project as a class library (I am using Entity Framework).
  5. Add a class and the code for this class is given below- 
  1. public class Users  
  2. {  
  3.     [Key]  
  4.     public int Id { getset; }  
  5.     public string Name { getset; }  
  6.     public string Address { getset; }  
  7.     public string Phone_Number { getset; }  
  8. }  

Now, right click on your class library and Install Entity Framework via NuGet.

Now, add the folder in the class library named as Context and add a Class in it, as given below-

  1. public class DBContext : DbContext  
  2.   {  
  3.       public DbSet<Users> ObjUser { getset; }  
  4.   }  
In Web.Config file of Project, add the following connection string- 
  1. <connectionStrings>  
  2.    <add name="DBContext" connectionString="Your Connection string" providerName="System.Data.SqlClient" />  
  3.  </connectionStrings>  
Now, add the class library in a reference of your project. Build the solution.

Now, right click on your project and Install Entity Framework via NuGet.

Add the Empty Controller in Controllers folder of the Project.

Add the following ActionResult Method to your Controller-
  1. public ActionResult Index()  
  2.        {  
  3.            using (DBContext context = new DBContext())  
  4.            {  
  5.                var Users = context.ObjUser.Take(5).ToList();     //At first i will show only 5 data per page so i had used Take(5)  
  6.                int UsersCount= Convert.ToInt32(Math.Ceiling((double)context.ObjUser.Count() / 5));    //Now calulating the required buttons for pagination  
  7.                TempData["Users"] = Users;            //Passing User details to view with TempData  
  8.                ViewBag.UsersCount = UsersCount;        //Count of button to be displayed  
  9.            }  
  10.            return View();  
  11.        }  
Now, in the view of Index method, I will show the list of Userdata retrieved in a table- 
  1. @{    
  2.     ViewBag.Title = "Index";    
  3.     var UsersData = TempData["Users"];   //Assigning the list of users to a variable    
  4. }    
  5. <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>    
  6.     
  7. <h2>Index</h2>    
  8.     
  9. <div>    
  10.     <table class="tablesorter">    
  11.         <thead>    
  12.             <tr>    
  13.                 <th>Name</th>    
  14.                 <th>Address</th>    
  15.                 <th>Phone_Number</th>    
  16.     
  17.             </tr>    
  18.         </thead>    
  19.         <tbody id="tbldisplay">    
  20.                
  21.                 @foreach (var p in (List<PaginationEntity.Users>)UsersData)    //PaginationEntity is my Class Library Name and Users is my model in that Libraray    
  22.                 {    
  23.                     <tr>    
  24.                         <td>@p.Name</td>    
  25.                         <td>@p.Address</td>    
  26.                         <td>@p.Phone_Number</td>    
  27.                     </tr>    
  28.                 }    
  29.               
  30.         </tbody>    
  31.     </table>    
  32.     <form>    
  33. //Here the number of buttons is to be displayed according the no os users shown per page    
  34.         <div id="SHowButton">    
  35.             @for (int i = 1; i <= ViewBag.UsersCount; i++)    
  36.             {    
  37. //SortData is a javascript function which is used for retrieving next or previous data according to page number    
  38.                 <input type="button" id="@i" value="@i" onclick="SortData(@i)" />      
  39.             }    
  40.         </div>    
  41. //Display is another Javascript Function used for showing number of users according to the value selected from dropdown     
  42.         <select class="pagesize" onchange="Display()" id="drpdwn">    
  43.             <option selected="selected" value="5">5</option>    
  44.             <option value="10">10</option>    
  45.             <option value="20">20</option>    
  46.             <option value="30">30</option>    
  47.             <option value="40">40</option>    
  48.         </select>      
  49.         <input type="text" id="Search"/>     //Used for searching user on keypress    
  50.     </form>       
  51. </div>    
Now, I will add a Display function, which will provide the list of the users, whose count will be the value selected from the dropdown. 
  1. <script>  
  2.     function Display() {  
  3. //Passing the value of dropdown to method Page in my Controller  
  4.         var data = $("#drpdwn").val();  
  5. //Here Home is my Controller and Page is JsonResult Method  
  6.         $.get("/Home/Page", { NumberOfData: data }, function (response) {  //NumberOfData is just an object whose value will be  - value of dropdown  
  7. //In response i will get the values returned by Page Method in controller  
  8. //I had returned users and Button Count  
  9.             if (response != null) {  
  10.                 $("#tbldisplay").empty();  
  11.                 $("#SHowButton").empty();  
  12.                 var datacontent = ""  
  13.                //appending the returned value  
  14.                 for (var i = 0; i < response.user.length; i++) {            //response.user is one of the returned value from  method       
  15.                     datacontent += "<tr><td>" + response.user[i].Name + "</td><td>" + response.user[i].Address + "</td><td>" + response.user[i].Phone_Number + "</td></tr>";  
  16.                 }  
  17.                  
  18.                 var ButtonContent = "";  
  19.                 alert(response.CountUser);  
  20.                 if (response.CountUser != 1) {  
  21.                     for (var d = 1; d <= response.CountUser; d++) {   
  22. // response.CountUser is another returned value from method  
  23.                         ButtonContent += "<input type='button' id=" + d + " value=" + d + " onclick='SortData(" + d + ")' />";  
  24.                     }  
  25.                     $("#SHowButton").append(ButtonContent);  
  26.                 }  
  27.                 $("#tbldisplay").append(datacontent);  
  28.                  
  29.             }  
  30.         });  
  31.     }  
  32. </script>  
Now, add JsonResult method "Page" in your Controller, as given below- 
  1. //as i am retreving data so httpget  
  2.  [HttpGet]  
  3.         public JsonResult Page(int NumberOfData)   //the object name should be same as used in JQuerry above it will get the value of dropdown  
  4.         {  
  5.             using (DBContext context = new DBContext())  
  6.             {  
  7.                 var Users = context.ObjUser.Take(NumberOfData).ToList();  //retreiving that much count of data  
  8.                 int UsersCount = Convert.ToInt32(Math.Ceiling((double)context.ObjUser.Count() / NumberOfData));  //again for required button count  
  9.                 var Result = new { user=Users,CountUser=UsersCount};  
  10. //here i am returning multiple data to my jquerry  user and CountUser  
  11.                 return Json(Result, JsonRequestBehavior.AllowGet);  
  12.             }  
  13.         }  
Now, for getting next or previous data on the button click, add JavaScript, as given below- 
  1.  function SortData(number)  //number will get the clicked button's number  
  2.     {  
  3.         var data = $("#drpdwn").val();  //passing current value of dropdwon  
  4. //SortData is my method on home controller  
  5.         $.get("/Home/SortData",{DrpDwnValue:data,PageNumber:number},function(response){  
  6.             if (response != null) {  
  7. //appending the fetched value to the table  
  8.                 $("#tbldisplay").empty();  
  9.                 var datacontent = ""  
  10.                 for (var i = 0; i < response.length; i++) {  
  11.                     datacontent += "<tr><td>" + response[i].Name + "</td><td>" + response[i].Address + "</td><td>" + response[i].Phone_Number + "</td></tr>";  
  12.                 }  
  13.                 $("#tbldisplay").append(datacontent);  
  14.             }  
  15.         });  
  16.     }  
Now, add a method in your controller to get the users list, according to the clicked button. 
  1.  [HttpGet]    
  2.         public JsonResult SortData(int DrpDwnValue,int PageNumber)    //match the name and order of the parameters with your javacript above    
  3.         {    
  4.             using (DBContext context = new DBContext())    
  5.             {    
  6. //here for skipping the current data displayed you have to use the OrderBy function of the IQueryable     
  7. //This will skip the current data and move to next or previous data according to the button you have clicked    
  8.                 var Users = context.ObjUser.OrderBy(x => x.Id).Skip(DrpDwnValue * (PageNumber - 1)).Take(DrpDwnValue).ToList();    
  9.                 return Json(Users, JsonRequestBehavior.AllowGet);    
  10.             }    
  11.         }    
For searching
 
I used the KeyUp function of JavaScript, as I want to search as the current text matches with any of the filled data, given below- 
  1. $("#Search").keyup(function (e) {    
  2.        clearTimeout($.data(this'timer'));    
  3.        if (e.keyCode == 13)    
  4.            MatchData(true);    
  5.        else    
  6.            $(this).data('timer', setTimeout(MatchData, 50));     //sets the timer between the key press from keyboard and the search    
  7.    })    
  8.    function MatchData(force)    
  9.    {    
  10.        var event = $("#Search").val();        //fetching the value from the textbox    
  11.     
  12.        $.get("/Home/SearchData", function (response) {    
  13.            //console.log(response);    
  14.            if (response.length) {    
  15.                $("#tbldisplay").empty();    
  16.     
  17.                var datacontent = "";    
  18.                for (var i = 0; i < response.length; i++) {    
  19. //Only the matching value will be displayed  
  20.                    if ((response[i].Name).indexOf(event) != -1 || (response[i].Address).indexOf(event) != -1 || (response[i].Phone_Number).indexOf(event) != -1) //Name , Address and Phone_number are my attributes in User Table {    
  21.                        datacontent += "<tr><td>" + response[i].Name + "</td><td>" + response[i].Address + "</td><td>" + response[i].Phone_Number + "</td></tr>";    
  22.                }    
  23.            }    
  24.            $("#tbldisplay").append(datacontent);    
  25.        });    
  26.    }   
Action Method 
  1. [HttpGet]  
  2.        public JsonResult SearchData()  
  3.        {  
  4.            using (DBContext context = new DBContext())  
  5.            {  
  6.                var Users = context.ObjUser.ToList();  
  7.                return Json(Users, JsonRequestBehavior.AllowGet);  
  8.            }  
  9.        }  
That's all for pagination, using JavaScript in MVC.


Similar Articles