In this article, I will show, how to make pagination with the retrieved data, using jQuery in MVC.
- Open Visual Studio. Select New Project.
- In Visual C# tab, select ASP.NET Web Application.
- Now, select an Empty Project. In "Add folders and core reference for:" section, select MVC. Select OK.
- Now, right click on your solution and another project as a class library (I am using Entity Framework).
- Add a class and the code for this class is given below-
- public class Users
- {
- [Key]
- public int Id { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- public string Phone_Number { get; set; }
- }
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-
- public class DBContext : DbContext
- {
- public DbSet<Users> ObjUser { get; set; }
- }
- <connectionStrings>
- <add name="DBContext" connectionString="Your Connection string" providerName="System.Data.SqlClient" />
- </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-
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-
- public ActionResult Index()
- {
- using (DBContext context = new DBContext())
- {
- var Users = context.ObjUser.Take(5).ToList(); //At first i will show only 5 data per page so i had used Take(5)
- int UsersCount= Convert.ToInt32(Math.Ceiling((double)context.ObjUser.Count() / 5)); //Now calulating the required buttons for pagination
- TempData["Users"] = Users; //Passing User details to view with TempData
- ViewBag.UsersCount = UsersCount; //Count of button to be displayed
- }
- return View();
- }
- @{
- ViewBag.Title = "Index";
- var UsersData = TempData["Users"]; //Assigning the list of users to a variable
- }
- <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
- <h2>Index</h2>
- <div>
- <table class="tablesorter">
- <thead>
- <tr>
- <th>Name</th>
- <th>Address</th>
- <th>Phone_Number</th>
- </tr>
- </thead>
- <tbody id="tbldisplay">
- @foreach (var p in (List<PaginationEntity.Users>)UsersData) //PaginationEntity is my Class Library Name and Users is my model in that Libraray
- {
- <tr>
- <td>@p.Name</td>
- <td>@p.Address</td>
- <td>@p.Phone_Number</td>
- </tr>
- }
- </tbody>
- </table>
- <form>
- //Here the number of buttons is to be displayed according the no os users shown per page
- <div id="SHowButton">
- @for (int i = 1; i <= ViewBag.UsersCount; i++)
- {
- //SortData is a javascript function which is used for retrieving next or previous data according to page number
- <input type="button" id="@i" value="@i" onclick="SortData(@i)" />
- }
- </div>
- //Display is another Javascript Function used for showing number of users according to the value selected from dropdown
- <select class="pagesize" onchange="Display()" id="drpdwn">
- <option selected="selected" value="5">5</option>
- <option value="10">10</option>
- <option value="20">20</option>
- <option value="30">30</option>
- <option value="40">40</option>
- </select>
- <input type="text" id="Search"/> //Used for searching user on keypress
- </form>
- </div>
- <script>
- function Display() {
- //Passing the value of dropdown to method Page in my Controller
- var data = $("#drpdwn").val();
- //Here Home is my Controller and Page is JsonResult Method
- $.get("/Home/Page", { NumberOfData: data }, function (response) { //NumberOfData is just an object whose value will be - value of dropdown
- //In response i will get the values returned by Page Method in controller
- //I had returned users and Button Count
- if (response != null) {
- $("#tbldisplay").empty();
- $("#SHowButton").empty();
- var datacontent = ""
- //appending the returned value
- for (var i = 0; i < response.user.length; i++) { //response.user is one of the returned value from method
- datacontent += "<tr><td>" + response.user[i].Name + "</td><td>" + response.user[i].Address + "</td><td>" + response.user[i].Phone_Number + "</td></tr>";
- }
- var ButtonContent = "";
- alert(response.CountUser);
- if (response.CountUser != 1) {
- for (var d = 1; d <= response.CountUser; d++) {
- // response.CountUser is another returned value from method
- ButtonContent += "<input type='button' id=" + d + " value=" + d + " onclick='SortData(" + d + ")' />";
- }
- $("#SHowButton").append(ButtonContent);
- }
- $("#tbldisplay").append(datacontent);
- }
- });
- }
- </script>
- //as i am retreving data so httpget
- [HttpGet]
- public JsonResult Page(int NumberOfData) //the object name should be same as used in JQuerry above it will get the value of dropdown
- {
- using (DBContext context = new DBContext())
- {
- var Users = context.ObjUser.Take(NumberOfData).ToList(); //retreiving that much count of data
- int UsersCount = Convert.ToInt32(Math.Ceiling((double)context.ObjUser.Count() / NumberOfData)); //again for required button count
- var Result = new { user=Users,CountUser=UsersCount};
- //here i am returning multiple data to my jquerry user and CountUser
- return Json(Result, JsonRequestBehavior.AllowGet);
- }
- }
- function SortData(number) //number will get the clicked button's number
- {
- var data = $("#drpdwn").val(); //passing current value of dropdwon
- //SortData is my method on home controller
- $.get("/Home/SortData",{DrpDwnValue:data,PageNumber:number},function(response){
- if (response != null) {
- //appending the fetched value to the table
- $("#tbldisplay").empty();
- var datacontent = ""
- for (var i = 0; i < response.length; i++) {
- datacontent += "<tr><td>" + response[i].Name + "</td><td>" + response[i].Address + "</td><td>" + response[i].Phone_Number + "</td></tr>";
- }
- $("#tbldisplay").append(datacontent);
- }
- });
- }
- [HttpGet]
- public JsonResult SortData(int DrpDwnValue,int PageNumber) //match the name and order of the parameters with your javacript above
- {
- using (DBContext context = new DBContext())
- {
- //here for skipping the current data displayed you have to use the OrderBy function of the IQueryable
- //This will skip the current data and move to next or previous data according to the button you have clicked
- var Users = context.ObjUser.OrderBy(x => x.Id).Skip(DrpDwnValue * (PageNumber - 1)).Take(DrpDwnValue).ToList();
- return Json(Users, JsonRequestBehavior.AllowGet);
- }
- }
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-
- $("#Search").keyup(function (e) {
- clearTimeout($.data(this, 'timer'));
- if (e.keyCode == 13)
- MatchData(true);
- else
- $(this).data('timer', setTimeout(MatchData, 50)); //sets the timer between the key press from keyboard and the search
- })
- function MatchData(force)
- {
- var event = $("#Search").val(); //fetching the value from the textbox
- $.get("/Home/SearchData", function (response) {
- //console.log(response);
- if (response.length) {
- $("#tbldisplay").empty();
- var datacontent = "";
- for (var i = 0; i < response.length; i++) {
- //Only the matching value will be displayed
- 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 {
- datacontent += "<tr><td>" + response[i].Name + "</td><td>" + response[i].Address + "</td><td>" + response[i].Phone_Number + "</td></tr>";
- }
- }
- $("#tbldisplay").append(datacontent);
- });
- }
Action Method
- [HttpGet]
- public JsonResult SearchData()
- {
- using (DBContext context = new DBContext())
- {
- var Users = context.ObjUser.ToList();
- return Json(Users, JsonRequestBehavior.AllowGet);
- }
- }

karishma sawantPosted Apr 26, 2020, 10:55 AM
I am new to mvc , pls suggest how to perform pagination without entity framework
Ravi KumarPosted Jun 28, 2018, 5:59 AM
Nicely explained. I have gone through one more pagedlist mvc ajax example. Must try this one hope it will be useful http://dotnettec.com/paging-in-mvc-using-jquery/