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; }
- }
In Web.Config file of Project, add the following connection string-
- <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-
- public ActionResult Index()
- {
- using (DBContext context = new DBContext())
- {
- var Users = context.ObjUser.Take(5).ToList();
- int UsersCount= Convert.ToInt32(Math.Ceiling((double)context.ObjUser.Count() / 5));
- TempData["Users"] = Users;
- ViewBag.UsersCount = UsersCount;
- }
- return View();
- }
Now, in the view of Index method, I will show the list of Userdata retrieved in a table-
- @{
- ViewBag.Title = "Index";
- var UsersData = TempData["Users"];
- }
- <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)
- {
- <tr>
- <td>@p.Name</td>
- <td>@p.Address</td>
- <td>@p.Phone_Number</td>
- </tr>
- }
-
- </tbody>
- </table>
- <form>
-
- <div id="SHowButton">
- @for (int i = 1; i <= ViewBag.UsersCount; i++)
- {
-
- <input type="button" id="@i" value="@i" onclick="SortData(@i)" />
- }
- </div>
-
- <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"/>
- </form>
- </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.
- <script>
- function Display() {
-
- var data = $("#drpdwn").val();
-
- $.get("/Home/Page", { NumberOfData: data }, function (response) {
-
-
- if (response != null) {
- $("#tbldisplay").empty();
- $("#SHowButton").empty();
- var datacontent = ""
-
- for (var i = 0; i < response.user.length; i++) {
- 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++) {
-
- ButtonContent += "<input type='button' id=" + d + " value=" + d + " onclick='SortData(" + d + ")' />";
- }
- $("#SHowButton").append(ButtonContent);
- }
- $("#tbldisplay").append(datacontent);
-
- }
- });
- }
- </script>
Now, add JsonResult method "Page" in your Controller, as given below-
-
- [HttpGet]
- public JsonResult Page(int NumberOfData)
- {
- using (DBContext context = new DBContext())
- {
- var Users = context.ObjUser.Take(NumberOfData).ToList();
- int UsersCount = Convert.ToInt32(Math.Ceiling((double)context.ObjUser.Count() / NumberOfData));
- var Result = new { user=Users,CountUser=UsersCount};
-
- return Json(Result, JsonRequestBehavior.AllowGet);
- }
- }
Now, for getting next or previous data on the button click, add JavaScript, as given below-
- function SortData(number)
- {
- var data = $("#drpdwn").val();
-
- $.get("/Home/SortData",{DrpDwnValue:data,PageNumber:number},function(response){
- if (response != null) {
-
- $("#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);
- }
- });
- }
Now, add a method in your controller to get the users list, according to the clicked button.
- [HttpGet]
- public JsonResult SortData(int DrpDwnValue,int PageNumber)
- {
- using (DBContext context = new DBContext())
- {
-
-
- 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));
- })
- function MatchData(force)
- {
- var event = $("#Search").val();
-
- $.get("/Home/SearchData", function (response) {
-
- if (response.length) {
- $("#tbldisplay").empty();
-
- var datacontent = "";
- for (var i = 0; i < response.length; i++) {
-
- if ((response[i].Name).indexOf(event) != -1 || (response[i].Address).indexOf(event) != -1 || (response[i].Phone_Number).indexOf(event) != -1)
- 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);
- }
- }
That's all for pagination, using JavaScript in MVC.