Saturday, August 10, 2019

Webgrid Paging, sorting and filtering in ASP.Net MVC

I have shown you, how we can implement custom paging in webgrid in ASP.NET MVC application.
Today, In this tutorial I will show you webgrid Paging, sorting and filtering functionality in asp.net MVC application.

It is an essential approach to using paging, sorting and filtering technique in applications where a lot of data to be loaded from a database. So here in this article, I have tried to show how we can do this
just following few simple steps.

Also nowadays, web page looks is very important and as we know bootstrap design is very popular, here in this article I have implemented bootstrap design in webgrid for making its looks perfect. 

You can see the below image, how the page will look like when you're done.


The column headings are links that the user can click to sort by that column and also showing sort arrow for showing current sort order. Clicking a column heading repeatedly toggles between ascending and descending sort order. 

Ok let start implement webgrid paging, sorting and filtering functionality with bootstrap looks in MVC application.

Follow the following steps in order to implement "Webgrid paging, sorting and filtering in ASP.NET MVC".

Here In this article, I have used Visual Studio 2013

Step - 1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Enter enter application name > select your project location > and then click on add button > It will brings up a new dialog window for select template > here I will select Empty template > checked  MVC checkbox from Add folder and core referances for: > and then click on ok button.

Step-2: Add required js & css library from NuGet.

Now I will add Jquery & Bootstrap CSS & JS library into our application.
Go to Solution Explorer > Right Click on Project name from Solution Explorer >  Manage NuGet packages > Search for Jquery for adding jquery library > Select the "jQuery" library and then click on Install button.

Sameway we will add Bootstrap CSS & JS library.

Step-3: Add a Database.

Now I will create a database for our application. As this is a tutorial project, I will add a database in our applications here in the app_data folder.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-4: Create a table in our database.

In this example, I have added the table for store Employee information for showing in webgrid.



double click on the database under app_data folder  for open the database in server explorer > expand the database and Right click on Tables node > click on Add New Table >  here we will write schema of the table for the table we want to create > now click on Update button for create the table and then again click on Update Database button. 

Step-5: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-6: Add a new class WebGridExtensions.cs

We need to just add 1 another class (WebGridExtensions.cs
) in our application.
We will get the class from this link : https://github.com/mdobie/WebGridPagerReplacement

Step-7: Add reference of System.Linq.Dynamic.


Add reference of System.Linq.Dynamic for dynamic sorting using string column name. Using 
System.Linq.Dynamic library we can do sorting using string column name & sort direction. We can do sorting like this data.OrderBy("FirstName desc") 


Go to solution explorer > Right click on Project Name > Manage NuGet packages > Search for System.Linq.Dynamic & install. 

Step-8: Create an MVC Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"

Step-9: Add a new method in HomeController.

Here I have added a method GetEmployees for fetch employees data from the database.  
  1. public List<Employee> GetEmployees(string search, string sort, string sortdir, int skip, int pageSize, out int totalRecord)
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. var v = (from a in dc.Employees
  6. where
  7. a.FirstName.Contains(search) ||
  8. a.LastName.Contains(search) ||
  9. a.EmailID.Contains(search) ||
  10. a.City.Contains(search) ||
  11. a.Country.Contains(search)
  12. select a
  13. );
  14. totalRecord = v.Count();
  15. v = v.OrderBy(sort + " " + sortdir);
  16. if (pageSize > 0)
  17. {
  18. v = v.Skip(skip).Take(pageSize);
  19. }
  20. return v.ToList();
  21. }
  22. }

Step-10: Write code in Index action of HomeController.

Now In this Index action we will write code for show employees data in webgrid. 
 
  1. public ActionResult Index(int page =1, string sort = "FirstName", string sortdir="asc", string search="")
  2. {
  3. int pageSize = 10;
  4. int totalRecord = 0;
  5. if (page < 1) page = 1;
  6. int skip = (page * pageSize) - pageSize;
  7. var data = GetEmployees(search, sort, sortdir, skip, pageSize, out totalRecord);
  8. ViewBag.TotalRows = totalRecord;
  9. ViewBag.search = search;
  10. return View(data);
  11. }

Step-11: Add view for Index action.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select "Empty" under Template dropdown  > > Add.
HTML Code 
  1. @model List<WebgridPagingSortingFiltering.Employee>
  2.  
  3. @{
  4. Layout = null;
  5. var grid = new WebGrid(canPage: true, rowsPerPage: 10);
  6. grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
  7. }
  8.  
  9. <!DOCTYPE html>
  10.  
  11. <html>
  12. <head>
  13. <meta name="viewport" content="width=device-width" />
  14. <title>Index</title>
  15. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
  16. </head>
  17. <body>
  18. <div class="container">
  19. <h2>Employees List</h2>
  20. <nav class="navbar navbar-default">
  21. <div class="container-fluid">
  22. <div class="navbar-header">
  23. <a href="#" class="navbar-brand">Search</a>
  24. </div>
  25. <div class="collapse navbar-collapse">
  26. @using (Html.BeginForm("index","home", FormMethod.Get,new{@class="navbar-form navbar-left"}))
  27. {
  28. <div class="form-group">
  29. <input type="text" name="search" value="@ViewBag.search" class="form-control" placeholder="search" />
  30. </div>
  31. <button type="submit" value="Search" class="btn btn-success">Search</button>
  32. }
  33. </div>
  34. </div>
  35. </nav>
  36. <div>
  37. @grid.Table(
  38. tableStyle: "table table-responsive table-bordered",
  39. columns: grid.Columns(
  40. grid.Column(columnName:"FirstName", header: "First Name"),
  41. grid.Column(columnName:"LastName", header: "Last Name"),
  42. grid.Column(columnName: "EmailID", header: "Email"),
  43. grid.Column(columnName: "City", header: "City"),
  44. grid.Column(columnName:"Country", header: "Country")
  45. )
  46. )
  47.  
  48. <div class="row">
  49. <div class="col-sm-6">
  50. @grid.PagerList(mode: WebGridPagerModes.All, paginationStyle: "pagination pagination-small pagination-right")
  51. </div>
  52. </div>
  53.  
  54. @Html.Hidden("dir", grid.SortDirection)
  55. @Html.Hidden("col", grid.SortColumn)
  56.  
  57. </div>
  58. </div>
  59. <script src="~/Scripts/jquery-3.1.1.js"></script>
  60. <script src="~/Scripts/bootstrap.min.js"></script>
  61. <script>
  62. $(function () {
  63. try {
  64. var dir = $('#dir').val();
  65. var col = $('#col').val();
  66. var header = $("th a[href*=" + col + "]");
  67. if (dir == "Ascending") {
  68. header.text(header.text() + " ▲")
  69. }
  70. if (dir == "Descending") {
  71. header.text(header.text() + " ▼");
  72. }
  73.  
  74. } catch (e) {
  75.  
  76. }
  77. })
  78. </script>
  79. </body>
  80. </html>

Step-12: Run Application.

We have done all the steps. Now it's time to run the application. 

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...