Skip to content Skip to sidebar Skip to footer

Datatables Method Start Again if New Request

ASP.NET

What is DataTables?

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.

Referenced from - https://datatables.internet/

Pre prerequisite for Application

  1. Visual Studio 2012 / 2013 / 2022 / 2017
  2. Entity Framework 5 and above
  3. SQL Server 2008

Let's commencement with database part first.

Database Part

I accept created a database with the name "Northwind" and in that, it has "Customers" table.

ASP.NET

Adjacent, we are going to create an ASP.NET MVC5 Web application.

Creating ASP.Net MVC5 Spider web Application

Open New Visual Studio 2022 IDE.

ASP.NET

Later opening IDE just, side by side we are going to create MVC project for doing that merely click File - inside that New - Project.

ASP.NET

After choosing a project, a new dialog volition pop up with the proper noun "New Projection". In that, we are going to cull Visual C# Project Templates - Spider web - ASP.Cyberspace Web Application. Then, nosotros are going to name the projection as "DemoDatatables".

ASP.NET

After naming the project nosotros are going click on OK button to create a project.

A new dialog will popular up for choosing templates for Creating "ASP.Cyberspace Web Application;" in that template, we are going to Create MVC application. That's why we are going to choose "MVC template" and adjacent click on OK button to create a projection.

ASP.NET

After clicking on OK button information technology volition outset to create a project.

Project Structure ASP.NET

Later creating project next, nosotros are going to create Model.

Creating Customer Model

We are going to add Customer Model to the Models binder.

ASP.NET

Code Snippet

  1. [Table( "Customers" )]
  2. public class  Customers
  3. {
  4.     [Key]
  5. public int ? CustomerID { get; fix; }
  6.     [Required(ErrorMessage ="Required CompanyName" )]
  7. public  string CompanyName { go; set; }
  8.     [Required(ErrorMessage ="Required ContactName" )]
  9. public  string ContactName { go; fix; }
  10.     [Required(ErrorMessage ="Required ContactTitle" )]
  11. public  string ContactTitle { become; prepare; }
  12. public  string Address { go; set; }
  13.     [Required(ErrorMessage ="Required City" )]
  14. public  string City { go; set; }
  15. public  string Region { get; prepare; }
  16.     [Required(ErrorMessage ="Required PostalCode" )]
  17. public  string PostalCode { get; gear up; }
  18.     [Required(ErrorMessage ="Required Country" )]
  19. public  string Land { become; ready; }
  20.     [Required(ErrorMessage ="Required Phone" )]
  21. public  string Telephone { get; prepare; }
  22. public  string Fax { go; prepare; }
  23. }

After calculation model side by side, we are going to employ Entity framework for accessing database to doing that we need to setup DbContext class.

Notation - What is DbContext?

DbContext is an important function of Entity Framework.

It is a span between your domain or entity classes and the database.

DbContext is the primary form that is responsible for interacting with data as an object.

Referenced from here.

Setting up DbContext Class

In this role, nosotros are first going to create a grade with name "DatabaseContext" and this grade will exist inheriting from "DbContext" class.

We are going create this class in Model Folder.

ASP.NET

Note
"DBConnection" is Connectedness string name.

Note - What is DBSet?

Referenced from hither.

DBSet form represents an entity ready that is used for creating, read, update, and delete operations. A generic version of DBSet (DbSet<TEntity>) tin can be used when the type of entity is not known at build fourth dimension.

Afterward adding "DatabaseContext" form next we are going to inherit this class with "DbContext" form.

After inheriting course next in constructor nosotros are going to create a connection for doing that we demand to pass connexion cord proper name to "DbContext" class, we are passing connection string name every bit DBConnection.

After passing connectedness string next we are going to declare DbSet in "DbContext" class which will help us to perform create, read, update, and delete operations.

Code Snippet

  1. namespace DemoDatatables.Models
  2. {
  3. public class  DatabaseContext : DbContext
  4.     {
  5. public  DatabaseContext() : base( "DBConnection" )
  6.         {
  7.         }
  8. public  DbSet<Customers> Customers {get; set;}
  9.     }
  10. }

Connexion cord in Web.config file

  1. <connectionStrings>
  2. <addname="DBConnection"
  3. connectionString="Data Source=####; initial catalog=Northwind; user id=sa; password=Pass####;"
  4. providerName="System.Data.SqlClient"  />
  5. </connectionStrings>

Next, we are going to add a controller.

Adding DemoController

In this part, we are going to add a new controller with the name "Demo".

ASP.NET

Afterwards we have clicked on Add button, it has created DemoController in Controller folder, every bit shown in the beneath view.

ASP.NET

After adding DemoController adjacent we are going to download DataTables Scripts and add it to project.

Getting DataTables Scripts

The post-obit Javascript library files are used in this example,

  • http://ajax.googleapis.com/ajax/libs/jquery/1.11.i/jquery.min.js
  • https://cdn.datatables.net/one.x.15/js/jquery.dataTables.min.js
  • https://cdn.datatables.cyberspace/1.ten.15/js/dataTables.bootstrap4.min.js

The following CSS files are used in this example,

Bootstrap v3.3.seven

https://getbootstrap.com/docs/3.3/getting-started/

DataTables CSS files

  • https://cdn.datatables.net/ane.10.15/css/dataTables.bootstrap.min.css
  • https://cdn.datatables.net/responsive/two.i.ane/css/responsive.bootstrap.min.css

Later on completing with downloading script and css next nosotros are going to add ShowGrid Action Method in DemoController.

Adding ShowGrid Action Method in Demo Controller ASP.NET

Subsequently adding Activeness Method now allow add View with proper noun "ShowGrid".

ASP.NET

Adding DataTables Filigree Scripts and Css on ShowGrid View

In get-go pace we are going to add together Script and Css reference.

  1. <script src= "//ajax.googleapis.com/ajax/libs/jquery/1.xi.1/jquery.min.js" ></script>
  2. <link href="~/Content/bootstrap.css"  rel= "stylesheet"  />
  3. <link href="https://cdn.datatables.internet/1.10.15/css/dataTables.bootstrap.min.css"  rel= "stylesheet"  />
  4. <link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css"  rel= "stylesheet"  />
  5. <script src="https://cdn.datatables.internet/1.10.xv/js/jquery.dataTables.min.js" ></script>
  6. <script src="https://cdn.datatables.net/1.ten.xv/js/dataTables.bootstrap4.min.js " ></script>

After adding Script and CSS reference side by side nosotros are going to add DataTables Markup.

Adding DataTables Markup

It is elementary Html Table in that we are going to add together columns headers ("<th>") with all the columns names which we want to display on the grid.

Afterwards adding Markup side by side, we are going to add DataTables function to Create DataTables.

  1. <div class = "container" >
  2.         <br />
  3.         <div style="width:ninety%; margin:0 auto;" >
  4.             <table id="demoGrid" class = "table table-striped table-bordered dt-responsive nowrap"  width= "100%"  cellspacing= "0" >
  5.                 <thead>
  6.               <tr>
  7.                 <th>CustomerID</th>
  8.                 <thursday>CompanyName</th>
  9.                 <th>ContactName</thursday>
  10.                 <th>ContactTitle</thursday>
  11.                 <thursday>Metropolis</th>
  12.                 <th>PostalCode</th>
  13.                 <thursday>Country</th>
  14.                 <th>Phone</th>
  15.                 <th>Edit</th>
  16.                 <th>Delete</thursday>
  17.             </tr>
  18.                 </thead>
  19.             </tabular array>
  20.         </div>
  21.     </div>

Adding DataTables Function to create DataTables

Lawmaking Snippet

  1. <script>
  2.     $('#demoGrid' ).dataTable({
  3.     });
  4. </script>

DataTables Options

All definitions are taken from https://datatables.net website.

  • Processing - Enable or disable the display of a 'processing' indicator when the table is beingness candy (e.chiliad. a sort).
  • server Side - Server-side processing - where filtering, paging, and sorting calculations are all performed by a server.
  • Filter - this option is used for enabling and disabling of search box
  • orderMulti - When ordering is enabled (ordering), by default DataTables allows users to sort multiple columns by shift-clicking upon the header prison cell for each column. Although this can be quite useful for users, it tin also increase the complication of the order, potentiality increasing the processing fourth dimension of ordering the data. Therefore, this pick is provided to allow this shift-click multiple column abilities
  • Ajax - Ajax asking is made to become data to DataTables.
  • columnDefs - Prepare column definition initialisation properties.
  • Columns - Set column specific initialisation backdrop.

After completing with an understanding of options or properties next nosotros are going to ready it.

We are going to set "processing" option to true to brandish processing bar, after that, we are going to gear up the "serverSide" option to truthful because we are going to do paging and filtering at serverSide.

Next options after "serverSide" option are "filter." We are going to utilize the search box; that's why we have set this holding to true, "orderMulti" is also set up to fake because we do non want to sort multiple columns at once.

DataTables Options snapshot ASP.NET

Ajax Selection

And the principal pick is Ajax which we are going to employ for calling an Activeness Method for getting data to bind DataTables Grid the data is in Json format. For that we are going to laissez passer URL: -"/Demo/LoadData", this asking is Mail service request. And data type we are going to set as Json.

We are going to call LoadData Activeness Method which is under Demo Controller which I will explain in upcoming steps.

ASP.NET

columnDefs Pick

After setting Ajax we have a "columnDefs" choice which I accept used for hiding Principal key of the table ("CustomerID") and which should besides be not searchable.

ASP.NET

columns Selection

Finally, the second to last choice is columns which are used for initialization of DataTables filigree. Add that belongings which yous demand to render on the filigree, which must be defined in this columns selection.

ASP.NET

Render buttons in Columns

At terminal, nosotros need to return button in the grid for editing information and deleting information.

ASP.NET

Finally, on click of the delete button, nosotros tin can call a custom function to delete data as I take created "DeleteData" function.

Complete code Snippet of ShowGrid View

  1. @{
  2.     Layout =null ;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7.     <meta name="viewport"  content= "width=device-width"  />
  8.     <title>ShowGrid</title>
  9.     <script src="//ajax.googleapis.com/ajax/libs/jquery/ane.11.ane/jquery.min.js" ></script>
  10.     <link href="~/Content/bootstrap.css"  rel= "stylesheet"  />
  11.     <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css"  rel= "stylesheet"  />
  12.     <link href="https://cdn.datatables.cyberspace/responsive/2.ane.1/css/responsive.bootstrap.min.css"  rel= "stylesheet"  />
  13.     <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js" ></script>
  14.     <script src="https://cdn.datatables.cyberspace/1.10.xv/js/dataTables.bootstrap4.min.js " ></script>
  15.     <script>
  16.         $(certificate).set(function  () {
  17.             $("#demoGrid" ).DataTable({
  18. "processing" : true ,
  19. "serverSide" : true ,
  20. "filter" : true ,
  21. "orderMulti" : fake ,
  22. "pageLength" : 5,
  23. "ajax" : {
  24. "url" : "/Demo/LoadData" ,
  25. "blazon" : "Mail service" ,
  26. "datatype" : "json"
  27.                 },
  28. "columnDefs" :
  29.                 [{
  30. "targets" : [0],
  31. "visible" : false ,
  32. "searchable" : fake
  33.                 },
  34.                 {
  35. "targets" : [vii],
  36. "searchable" : imitation ,
  37. "orderable" : simulated
  38.                 },
  39.                 {
  40. "targets" : [viii],
  41. "searchable" : false ,
  42. "orderable" : fake
  43.                 },
  44.                 {
  45. "targets" : [ix],
  46. "searchable" : fake ,
  47. "orderable" : false
  48.                 }],
  49. "columns" : [
  50.                       {"data" : "CustomerID" , "proper name" : "CustomerID" , "autoWidth" : truthful  },
  51.                       {"information" : "CompanyName" , "proper noun" : "CompanyName" , "autoWidth" : truthful  },
  52.                       {"information" : "ContactName" , "title" : "ContactName" , "name" : "ContactName" , "autoWidth" : true  },
  53.                       {"data" : "ContactTitle" , "proper noun" : "ContactTitle" , "autoWidth" : true  },
  54.                       {"information" : "City" , "name" : "City" , "autoWidth" : truthful  },
  55.                       {"data" : "PostalCode" , "proper noun" : "PostalCode" , "autoWidth" : truthful  },
  56.                       {"information" : "Country" , "name" : "Country" , "autoWidth" : true  },
  57.                       {"information" : "Phone" , "proper name" : "Phone" , "title" : "Status" , "autoWidth" : true  },
  58.                       {
  59. "render" : office  (data, blazon, full, meta)
  60.                           {return '<a class="btn btn-info" href="/Demo/Edit/'  + full.CustomerID + '">Edit</a>' ; }
  61.                       },
  62.                        {
  63.                            data:null , render: function  (information, type, row) {
  64. return "<a href='#' class='btn btn-danger' onclick=DeleteData('"  + row.CustomerID + "'); >Delete</a>" ;
  65.                            }
  66.                        },
  67.                 ]
  68.             });
  69.         });
  70.     </script>
  71. </caput>
  72. <torso>
  73.     <divclass = "container" >
  74.         <br />
  75.         <div style="width:90%; margin:0 car;" >
  76.             <table id="demoGrid" class = "table table-striped table-bordered dt-responsive nowrap"  width= "100%"  cellspacing= "0" >
  77.                 <thead>
  78.                     <tr>
  79.                         <thursday>CustomerID</th>
  80.                         <thursday>CompanyName</th>
  81.                         <th>ContactName</th>
  82.                         <thursday>ContactTitle</th>
  83.                         <th>City</th>
  84.                         <thursday>PostalCode</th>
  85.                         <th>Country</th>
  86.                         <th>Telephone</thursday>
  87.                         <th>Edit</th>
  88.                         <th>Delete</th>
  89.                     </tr>
  90.                 </thead>
  91.             </table>
  92.         </div>
  93.     </div>
  94. </body>
  95. </html>

After completing with initialization of DataTables grid adjacent we are going to create LoadData Action Method.

Adding LoadData Action Method to Demo Controller

Hither we are going to Add Action Method with name LoadData. In this action method, we are going to go all Customer records from the database to display and on the basis of the parameter nosotros are going sort data, and do paging with data.

We are doing paging and filtering of data on the server side; that why we are using IQueryable which volition execute queries with filters on the server side.

ASP.NET

For using OrderBy in the query we need to install System.Linq.Dynamic packet from NuGet packages.

Snapshot while adding System.Linq.Dynamic package from NuGet packages ASP.NET

After calculation the package, next, we come across the consummate code snippet and how to go data and do paging and filtering with it.

Complete code Snippet of LoadData Activity Method

All processes are step by step with comments; so it'southward like shooting fish in a barrel to sympathise.

All Asking.Form.GetValues parameters value will get populated when AJAX post method gets called on a load of if you practise paging or sorting and search.

Code Snippet

  1. public  ActionResult LoadData()
  2. {
  3. try
  4.     {
  5. var  draw = Request.Form.GetValues( "depict" ).FirstOrDefault();
  6. var  start = Request.Course.GetValues( "start" ).FirstOrDefault();
  7. var  length = Asking.Grade.GetValues( "length" ).FirstOrDefault();
  8. var  sortColumn = Request.Course.GetValues( "columns["  + Asking.Form.GetValues( "order[0][cavalcade]" ).FirstOrDefault() + "][name]" ).FirstOrDefault();
  9. var  sortColumnDir = Request.Form.GetValues( "order[0][dir]" ).FirstOrDefault();
  10. var  searchValue = Request.Form.GetValues( "search[value]" ).FirstOrDefault();
  11. int  pageSize = length != zippo  ? Convert.ToInt32(length) : 0;
  12. int  skip = start != null  ? Convert.ToInt32(start) : 0;
  13. int  recordsTotal = 0;
  14. var  customerData = (from tempcustomer in  _context.Customers
  15.                             select tempcustomer);
  16. if  (!(string.IsNullOrEmpty(sortColumn) && cord.IsNullOrEmpty(sortColumnDir)))
  17.         {
  18.             customerData = customerData.OrderBy(sortColumn +" "  + sortColumnDir);
  19.         }
  20. if  (!string.IsNullOrEmpty(searchValue))
  21.         {
  22.             customerData = customerData.Where(m => m.CompanyName == searchValue);
  23.         }
  24.         recordsTotal = customerData.Count();
  25. var  data = customerData.Skip(skip).Take(pageSize).ToList();
  26. return  Json( new  { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = information });
  27.     }
  28. catch  (Exception)
  29.     {
  30. throw ;
  31.     }
  32. }

Complete code Snippet of DemoController

  1. using DemoDatatables.Models;
  2. using System;
  3. using System.Linq;
  4. using System.Spider web.Mvc;
  5. using System.Linq.Dynamic;
  6. using System.Data.Entity;
  7. namespace DemoDatatables.Controllers
  8. {
  9. public course  DemoController : Controller
  10.     {
  11. public  ActionResult ShowGrid()
  12.         {
  13. return  View();
  14.         }
  15. public  ActionResult LoadData()
  16.         {
  17. attempt
  18.             {
  19.                 using (DatabaseContext _context =new  DatabaseContext())
  20.                 {
  21. var  depict = Request.Grade.GetValues( "draw" ).FirstOrDefault();
  22. var  start = Request.Grade.GetValues( "start" ).FirstOrDefault();
  23. var  length = Request.Form.GetValues( "length" ).FirstOrDefault();
  24. var  sortColumn = Request.Course.GetValues( "columns["  + Request.Form.GetValues( "club[0][cavalcade]" ).FirstOrDefault() + "][name]" ).FirstOrDefault();
  25. var  sortColumnDir = Request.Form.GetValues( "club[0][dir]" ).FirstOrDefault();
  26. var  searchValue = Asking.Course.GetValues( "search[value]" ).FirstOrDefault();
  27. int  pageSize = length != nix  ? Convert.ToInt32(length) : 0;
  28. int  skip = beginning != null  ? Catechumen.ToInt32(start) : 0;
  29. int  recordsTotal = 0;
  30. var  customerData = (from tempcustomer in  _context.Customers
  31.                                         select tempcustomer);
  32. if  (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
  33.                     {
  34.                         customerData = customerData.OrderBy(sortColumn +" "  + sortColumnDir);
  35.                     }
  36. if  (!cord.IsNullOrEmpty(searchValue))
  37.                     {
  38.                         customerData = customerData.Where(m => thou.CompanyName == searchValue);
  39.                     }
  40.                     recordsTotal = customerData.Count();
  41. var  information = customerData.Skip(skip).Accept(pageSize).ToList();
  42. render  Json( new  { depict = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = information });
  43.                 }
  44.             }
  45. take hold of  (Exception)
  46.             {
  47. throw ;
  48.             }
  49.         }
  50.     }
  51. }

Save the entire Source code and run the application.

Run Application

To admission the application, enter URL - http://localhost:#####/demo/showgrid .

"#####" is localhost port number.

ASP.NET

Existent-fourth dimension Debugging Snapshot

In this section, yous can see what values are populated when mail service method gets chosen.

ASP.NET

Search with DataTables grid

In this section we take implemented a search for only Companyname cavalcade, if yous desire to add another column just use or status ("||") with it.

ASP.NET

Calculation more columns to search ASP.NET

Snapshot while Search Information ASP.NET

Debugging View of Search ASP.NET

Later on completing with search Implementation next nosotros are going to piece of work on Edit Button of DataTables Grid.

Edit Event in DataTables filigree

In this section first nosotros are going add Edit Action Method in Demo Controller which will handle edit request and it will take Client ID as input from which we are going to become details of that client.

Code Snippet of Edit Action Method

  1. [HttpGet]
  2. public  ActionResult Edit( int ? ID)
  3. {
  4. effort
  5.     {
  6.         using (DatabaseContext _context =new  DatabaseContext())
  7.         {
  8. var  Customer = (from customer in  _context.Customers
  9.                             where customer.CustomerID == ID
  10.                             select customer).FirstOrDefault();
  11. return  View(Customer);
  12.         }
  13.     }
  14. catch  (Exception)
  15.     {
  16. throw ;
  17.     }
  18. }

Later having a look on Edit action method next let'southward run into how to render Edit link (button).

Below is syntax for rendering Edit button

ASP.NET

Finally, you tin see Edit View below.

Edit View ASP.NET

After completing with Edit office next we are going to accept a look at delete part.

Delete Event in DataTables filigree

In this section first we are going add DeleteCustomer Action Method in DemoController which will handle delete asking and it will take Client ID ("ID") every bit input from which we are going to delete customer data.

Code Snippet of DeleteCustomer

  1. [HttpPost]
  2. public  JsonResult DeleteCustomer( int ? ID)
  3. {
  4.     using (DatabaseContext _context =new  DatabaseContext())
  5.     {
  6. var  customer = _context.Customers.Find(ID);
  7. if  (ID == zilch )
  8. return  Json(data: "Not Deleted" , behavior: JsonRequestBehavior.AllowGet);
  9.         _context.Customers.Remove(customer);
  10.         _context.SaveChanges();
  11. return  Json(data: "Deleted" , behavior: JsonRequestBehavior.AllowGet);
  12.     }
  13. }

After having a look on DeleteCustomer action method next permit'southward see how to render delete link (button).

Below is syntax for rendering Delete button ASP.NET

Now you can come across that we are generating elementary href push button and on that button, nosotros accept added an onclick effect to call DeleteData function which we have non created yet, and so  allow'due south create DeleteData function.

Code Snippet

In this part when user clicks on Delete button DeleteData function volition get chosen and commencement thing information technology volition show is confirmation alarm ("Are y'all sure you want to delete ...?") if y'all click on ok (ostend) button then it will call Delete function. This office takes CustomerID as input, side by side we are generating URL of DeleteCustomer Action Method and passing it as ajax post request and forth with it we are passing Customer ID as parameter.

If data is deleted, then we are going to get "Deleted" as a response from Deletecustomer Activity Method, finally, we show alert to the user and reload grid.

  1. <script>
  2. office  DeleteData(CustomerID) {
  3. if  (confirm( "Are you sure you want to delete ...?" )) {
  4.             Delete(CustomerID);
  5.         }
  6. else  {
  7. render faux ;
  8.         }
  9.     }
  10. office  Delete(CustomerID) {
  11. var  url = '@Url.Content("~/")'  + "Demo/DeleteCustomer" ;
  12.         $.post(url, { ID: CustomerID },function  (data) {
  13. if  (data == "Deleted" ) {
  14.                 alert("Delete Client !" );
  15.                 oTable = $('#demoGrid' ).DataTable();
  16.                 oTable.describe();
  17.             }
  18. else  {
  19.                 alert("Something Went Incorrect!" );
  20.             }
  21.         });
  22.     }
  23. </script>

Snapshot while deleting customer ASP.NET

Debugging View while deleting customer ASP.NET

Finally, nosotros have learned how to use jQuery DataTables Grid with ASP.NET Core MVC. I hope you enjoyed the article.

hammonssucan1968.blogspot.com

Source: https://www.c-sharpcorner.com/article/using-datatables-grid-with-asp-net-mvc/

Post a Comment for "Datatables Method Start Again if New Request"