Jquery Datatable How to Sort Again After Editable Column
Introduction
In this commodity, we are going to learn how to employ a Client-side Filigree (DataTables Grid) with ASP.Internet Cadre MVC in a step-past-step fashion. A few months back, while interviewing for my company, I asked nigh developers what kind of Grids they were using in their current project. Most people answered with: a "DataTables Filigree". The next question was, why? The answer was: "Considering information technology is like shooting fish in a barrel to use and it is open-source".
Now, in this ongoing era of web development, well-nigh of the work is done at the Customer-side and less work is washed on the server-side.
As you know, there are no inbuilt Grids in ASP.Internet Cadre. You need to either create your own or use third-party Grids available from the NuGet package. The best selection is to employ the customer-side filigree. In this article, I am going to use the jQuery DataTables Grid.
Let'due south starting time with the database part first.
Database Office
I have created a database with the name "CustomerDB". In that, it has a "CustomerTB" table.
Adjacent, nosotros are going to create an ASP.Internet Core MVC Web application.
Creating ASP.NET Core MVC Web Application
Open a New Visual Studio 2017 IDE.
After opening IDE, next, we are going to create the ASP.Cyberspace Core MVC project. For that, just click on File >> New >> Project.
Subsequently choosing a project, a new dialog will popular up with the name "New Project". In that, we are going to choose Visual C# Projection Templates >> Spider web >> ASP.NET Cadre Web Application. And then, nosotros are going to name the project "ExampleGrid".
Subsequently naming the project, we are going to click on the OK button to create a project. A new dialog will pop up for choosing templates in order to create an "ASP.NET Core Spider web Application". In that template, we are going to create an MVC application. That's why we are going to choose "Web Application (Model View Controller)". Next, we will take the option to cull framework 1.) Net core, or, 2.) .Cyberspace Framework. Also, there's the ASP.Net Cadre Version. For that, we are going to choose ".Internet Framework" and "ASP.Net Core i.1" every bit the ASP.Cyberspace Core Version. Click on the OK button to create a projection.
After clicking on the OK push, it will showtime to create a project.
Project Structure
Installing the Package for Entity Framework Core from NuGet
To install the bundle, but right click on the project (ExampleGrid) and then select Manage NuGet bundle. The beneath dialog of the NuGet Package Director will pop up.
In the browse tab, blazon "Microsoft.EntityFrameworkCore.SqlServer" in the search box and merely click on the Install push button.
Microsoft.EntityFrameworkCore.SqlServer
Adding a Connection String and Setting Up DbContext
Afterwards adding a reference, now add together a connexion string in the appsetting.json file.
After adding a connexion string, the side by side stride is to add a class that will inherit the DbContext grade. Before doing this, permit's start with creating a folder for models. Inside that, we are going to add this class.
For adding a folder, just right click on the project (ExampleGrid), then choose Add from the card that pops up. Inside that, choose New Binder.
Add - New Folder.
Now, allow's add a class with the name DatabaseContext in the Models binder.
For calculation a model, just right click on the Models folder. And so, select Add >> Class. An "Add New Item" dialog will pop up with the default grade selected. Name the form as DatabaseContext and click on the Add push.
Afterwards adding a DatabaseContext class, next, we are going to inherit the DbContext course.
After inheriting with DbContext, next we are creating a constructor which takes DbContextOptions equally an input parameter and also inherits the base class constructor (: base of operations(options)) [DbContext].
Next, we are going to add together a new Service in Startup.cs class for injecting dependency.
Now, whenever you use DatabaseContext class, the DbContext instance will be injected there.
Adding Model CustomerTB
Adding DbSet for CustomerTB Model in DatabaseContext class
Now, allow's add DbSet for CustomerTB Model in DatabaseContext grade, equally shown beneath.
After adding CustomerTB Model in DatabaseContext form next step we are going to create a controller.
After nosotros click on the Add button, it has created DemoGridController in the Controller folder, as shown in the beneath screenshot.
Later on calculation DemoGridController, next, we are going to download DataTables Scripts and add it to the project.
Getting DataTables Scripts
The post-obit Javascript library files are used in this instance:
- http://ajax.googleapis.com/ajax/libs/jquery/1.xi.1/jquery.min.js
- https://cdn.datatables.internet/1.10.15/js/jquery.dataTables.min.js
- https://cdn.datatables.net/1.x.xv/js/dataTables.bootstrap4.min.js
The post-obit CSS files are used in this example:
Bootstrap v3.3.seven
https://getbootstrap.com/docs/3.iii/getting-started/
DataTables CSS files
https://cdn.datatables.net/1.10.xv/css/dataTables.bootstrap.min.css https://cdn.datatables.net/responsive/ii.1.i/css/responsive.bootstrap.min.css
Calculation ShowGrid Action Method in DemoGrid Controller
Adding ShowGrid View in DemoGrid Binder
In the offset step, we are going to add Script and Css references.
- <script src= "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script>
- <link href="~/lib/bootstrap/dist/css/bootstrap.css" rel= "stylesheet" />
- <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel= "stylesheet" />
- <link href="https://cdn.datatables.cyberspace/responsive/2.1.1/css/responsive.bootstrap.min.css" rel= "stylesheet" />
- <script src="https://cdn.datatables.net/1.10.fifteen/js/jquery.dataTables.min.js" ></script>
- <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js " ></script>
After adding Script and CSS references, adjacent, nosotros are going to add a Datatables Markup.
Adding DataTables Markup
This is a simple HTML Table where we are going to add column headers, ("<thursday>"), which will show all columns names that we desire to display.
- <div class = "container" >
- <br />
- <div style="width:xc%; margin:0 motorcar;" >
- <tabular array id="example" class = "table table-striped table-bordered dt-responsive nowrap" width= "100%" cellspacing= "0" >
- <thead>
- <tr>
- <th>CustomerID</th>
- <th>Proper noun</th>
- <thursday>Address</th>
- <th>Country</th>
- <th>City</th>
- <th>Phoneno</thursday>
- <th>Edit</th>
- <th>Delete</thursday>
- </tr>
- </thead>
- </table>
- </div>
- </div>
After adding Markup, next nosotros are going to add a datatables function to create datatables.
Adding DataTables Function to Create DataTables
Bones syntax:
- $( '#example' ).dataTable( {
- } );
DataTables Options
All definitions are taken from the https://datatables.net website.
- Processing - Enables or disables the brandish of a 'processing' indicator when the table is being processed (east.1000. a sort).
- serverSide - 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 the search box
- orderMulti - When ordering is enabled (ordering), by default DataTables allows users to sort multiple columns by shift-clicking upon the header cell for each column. Although this tin can be quite useful for users, it can also increase the complexity of the order, potentially increasing the processing fourth dimension of ordering the information. Therefore, this selection is provided to allow this shift-click multiple column power
- Ajax - Ajax request is made to go information to DataTables.
- columnDefs - Set column definition initialisation properties.
- Columns - Set column specific initialization properties.
After completing an understanding of options or properties next we are going to set it.
We are going to set the "processing" option to true to display processing bar, afterwards that, we are going to gear up the "serverSide" option to truthful considering we are going to do paging and filtering at the serverSide.
The next choice afterward the "serverSide" option is "filter." We are going to use the search box; that'south why we have set this belongings to true, "orderMulti" is too fix to faux because we do not want to sort multiple columns at once.
DataTables Options Snapshot
The main option is Ajax, which we are going to use for calling an Action Method for getting data to bind the DataTables Grid. The data is in JSON format. For that, we are going to pass the URL: -"/DemoGrid/LoadData". This request is a Post asking. We are going to set the data type every bit JSON.
Side by side, we are going to call the LoadData Activity Method, which is under the DemoGrid Controller that I will explain in the upcoming steps.
E.grand.
columnDefs Option
After setting Ajax, we have a "columnDefs" option that I have used for hiding the Primary key of the table ("CustomerID") and that should as well exist unsearchable.
Eastward.chiliad.
columns Option
Finally, the second to last option is columns that are used for the initialization of the DataTables filigree. Add the property that you demand to render on the grid, which must be defined in this columns pick.
Due east.g.
Render Buttons in Columns
Finally, we demand to return a push in the grid for editing and deleting information.
Finally, when clicking the delete button, we can telephone call a custom function to delete information, as I have created the "DeleteData" function.
Consummate Code Snippet of ShowGrid View
- @ {
- Layout =nada ;
- }
- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.i/jquery.min.js" ></script>
- <link href ="~/lib/bootstrap/dist/css/bootstrap.css" rel = "stylesheet" / >
- <link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel= "stylesheet" />
- <link href ="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel = "stylesheet" / >
- <script src="https://cdn.datatables.cyberspace/1.10.15/js/jquery.dataTables.min.js" ></script>
- <script src ="https://cdn.datatables.net/ane.10.15/js/dataTables.bootstrap4.min.js" >< /script>
- <divclass = "container" >
- <br />
- <div style ="width:ninety%; margin:0 automobile;" >
- <table id="example" class = "table table-striped table-bordered dt-responsive nowrap" width= "100%" cellspacing= "0" >
- <thead>
- <tr>
- <th>CustomerID</th>
- <th>Name</th>
- <th>Accost</thursday>
- <thursday>Country</th>
- <th>City</thursday>
- <th>Phoneno</th>
- <th>Edit</th>
- <th>Delete</th>
- </tr>
- </thead>
- </tabular array>
- </div>
- </div>
- <script>
- $(document).set up(function() {
- $("#case" ).DataTable({
- "processing" : true ,
- "serverSide" : true ,
- "filter" : true ,
- "orderMulti" : false ,
- "ajax" : {
- "url" : "/DemoGrid/LoadData" ,
- "blazon" : "POST" ,
- "datatype" : "json"
- },
- "columnDefs" : [{
- "targets" : [0],
- "visible" : false ,
- "searchable" : false
- }],
- "columns" : [
- {"information" : "CustomerID" , "proper noun" : "CustomerID" , "autoWidth" : truthful },
- {"information" : "Name" , "name" : "Name" , "autoWidth" : true },
- {"data" : "Address" , "name" : "Accost" , "autoWidth" : true },
- {"data" : "State" , "name" : "Country" , "autoWidth" : true },
- {"information" : "City" , "name" : "Urban center" , "autoWidth" : true },
- {"data" : "Phoneno" , "name" : "Phoneno" , "autoWidth" : true },
- {
- "render" : function(information, type, full, meta) { return '<a grade="btn btn-info" href="/DemoGrid/Edit/' + total.CustomerID + '">Edit</a>' ; }
- },
- {
- data:null ,
- render: function(data, type, row) {
- return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.CustomerID + "'); >Delete</a>" ;
- }
- },
- ]
- });
- });
- office DeleteData(CustomerID) {
- if (confirm( "Are you sure yous desire to delete ...?" )) {
- Delete(CustomerID);
- }else {
- render false ;
- }
- }
- part Delete(CustomerID) {
- var url ='@Url.Content("~/")' + "DemoGrid/Delete" ;
- $.postal service(url, { ID: CustomerID }, function(information) {
- if (data) {
- oTable = $('#example' ).DataTable();
- oTable.draw();
- }else {
- warning("Something Went Incorrect!" );
- }
- });
- }
- </script>
After finishing the initialization of the DataTables grid, next we are going to create a LoadData Action Method.
Adding LoadData Action Method to DemoGrid Controller
Here, we are going to Add together an Action Method with the name LoadData. In this action method, we are going to get all Customer records from the database to display. On the basis of the parameter, we 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 will execute queries with filters on the server-side.
For using OrderBy in the query, we demand to install System.Linq.Dynamic package from NuGet packages.
Afterward adding the packet, next, we encounter the complete code snippet and how to go data and do paging and filtering with information technology.
Complete code Snippet of LoadData Action Method
All processes are step-by-step with comments, then it's easy to sympathize.
All Request.Class parameters value will get populated when AJAX post method gets called on load.
- public IActionResult LoadData()
- {
- try
- {
- var depict = HttpContext.Request.Form[ "draw" ].FirstOrDefault();
- var start = Request.Course[ "starting time" ].FirstOrDefault();
- var length = Request.Form[ "length" ].FirstOrDefault();
- var sortColumn = Request.Course[ "columns[" + Request.Form[ "social club[0][cavalcade]" ].FirstOrDefault() + "][name]" ].FirstOrDefault();
- var sortColumnDirection = Request.Form[ "guild[0][dir]" ].FirstOrDefault();
- var searchValue = Asking.Form[ "search[value]" ].FirstOrDefault();
- int pageSize = length != null ? Convert.ToInt32(length) : 0;
- int skip = showtime != nix ? Convert.ToInt32(start) : 0;
- int recordsTotal = 0;
- var customerData = (from tempcustomer in _context.CustomerTB
- select tempcustomer);
- if (!(string.IsNullOrEmpty(sortColumn) && cord.IsNullOrEmpty(sortColumnDirection)))
- {
- customerData = customerData.OrderBy(sortColumn +" " + sortColumnDirection);
- }
- if (!string.IsNullOrEmpty(searchValue))
- {
- customerData = customerData.Where(m => m.Name == searchValue);
- }
- recordsTotal = customerData.Count();
- var information = customerData.Skip(skip).Accept(pageSize).ToList();
- return Json( new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
- }
- catch (Exception)
- {
- throw ;
- }
- }
Complete code Snippet of DemoGridController
In this part, we are using constructor injection to inject DBContext dependencies. By using DBContext, we are getting all customer data from the database.
- using System;
- using Organization.Collections.Generic;
- using Organization.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using ExampleGrid.Models;
- using Organisation.Linq.Dynamic;
- namespace ExampleGrid.Controllers
- {
- public class DemoGridController : Controller
- {
- individual DatabaseContext _context;
- public DemoGridController(DatabaseContext context)
- {
- _context = context;
- }
- public IActionResult ShowGrid()
- {
- return View();
- }
- public IActionResult LoadData()
- {
- try
- {
- var draw = HttpContext.Request.Form[ "describe" ].FirstOrDefault();
- var beginning = Request.Form[ "start" ].FirstOrDefault();
- var length = Request.Form[ "length" ].FirstOrDefault();
- var sortColumn = Asking.Form[ "columns[" + Asking.Form[ "order[0][column]" ].FirstOrDefault() + "][name]" ].FirstOrDefault();
- var sortColumnDirection = Request.Form[ "order[0][dir]" ].FirstOrDefault();
- var searchValue = Request.Form[ "search[value]" ].FirstOrDefault();
- int pageSize = length != nil ? Convert.ToInt32(length) : 0;
- int skip = showtime != null ? Convert.ToInt32(starting time) : 0;
- int recordsTotal = 0;
- var customerData = (from tempcustomer in _context.CustomerTB
- select tempcustomer);
- if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
- {
- customerData = customerData.OrderBy(sortColumn +" " + sortColumnDirection);
- }
- if (!string.IsNullOrEmpty(searchValue))
- {
- customerData = customerData.Where(m => chiliad.Name == searchValue);
- }
- recordsTotal = customerData.Count();
- var information = customerData.Skip(skip).Have(pageSize).ToList();
- return Json( new { describe = describe, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
- }
- grab (Exception)
- {
- throw ;
- }
- }
- }
- }
Relieve the entire Source code and run the awarding.
Run Application
To access the application, enter URL - http://localhost:#####/demogrid/showgrid.
"#####" is a localhost port number.
Existent-time Debugging Snapshot
In this department, yous tin can run across the values that are populated when the post method is chosen.
Search with DataTables grid
In this section, we have implemented a search for simply the Proper noun column. If yous want to add another column, simply use or condition ("||") with information technology.
Adding More than Columns to Search
Search demo
Edit and Delete with Confirmation in DataTables Grid
In this section, nosotros are focusing on two buttons edit and delete. Edit is used for editing records. In this part, you but need to provide a URL of the edit page with its parameter.
Below is the Syntax for Rendering Edit Button
For the delete button, we can but do the same style as Edit but for that, we demand to create another page. However, if we want a line deleted, then we demand to apply the below syntax for rendering the button.
Below is the syntax for Rendering a Delete Button
- <script>
- office DeleteData(CustomerID)
- {
- if (ostend( "Are you sure yous want to delete ...?" ))
- {
- Delete(CustomerID);
- }
- else
- {
- return false ;
- }
- }
- part Delete(CustomerID)
- {
- var url = '@Url.Content("~/")' + "DemoGrid/Delete" ;
- $.post(url, { ID: CustomerID },part (data)
- {
- if (information)
- {
- oTable = $('#instance' ).DataTable();
- oTable.draw();
- }
- else
- {
- warning("Something Went Wrong!" );
- }
- });
- }
- </script>
Finally, we take learned how to use the jQuery DataTables Grid with ASP.NET CORE MVC. I hope you lot enjoyed this article.
reeddreasockinly80.blogspot.com
Source: https://www.c-sharpcorner.com/article/using-jquery-datatables-grid-with-asp-net-core-mvc/
Post a Comment for "Jquery Datatable How to Sort Again After Editable Column"