ASP.NET Core - Using JQuery DataTables
Hello.
Sometimes when we want to create an application we want to use plugins and not reinvent the wheel, in the case of showing information through tables there’s a very cool plugin (open source, very flexible and extensive), called DataTables (jquery plugin). We are going to create an asp.net core web application, then we create an api which is going to request information from a collection (like a database).
The DataTables site has a detailed and useful documentation, there’s a section related to getting information “server-side” in case you want to go deeper after reading this post.
In Server side approach we make an ajax request to the server and receive information using jquery.
Let’s start…
First we are going to create an asp.net core application. Create a blank solution, then create a new project
Choose .net core category, select asp.net core web application and give a name
We select the Web Application Template
Adding and Configuring DataTatables
Now we are going to install datatables. The only library dependency is JQuery (using this web template we already have it)
Dependencies for DataTables
There is a css library, it’s optional, it gives us a default styling. DataTables library is very flexible and we can use any other styling framework (like foundation, bootstrap, material, etc, check here), we are going to use the default way.
Let’s add some sections in the layout view to add required files.
I could add directly the libraries in layout but in this case I want to show you the other way, so we are going to create two sections (styles and scripts) to add the css file and js file in the view to be more specific when loading the libraries.
Inside head tag add1
@RenderSection(“styles”, required: false)
At the end of body tag add1
@RenderSection(“scripts”, required : false)
We are going to navigate through Home/Index view and remove some auto-generated code.
Let’s remove all of this code
We are going to have something like this in Home/Index view (or whichever order you want to have)
Let’s add a reference to the datatable style
The very basic table structure (installation) we need is something like this one
In the js side
So as you see the table id is very important.
Let’s add the table structure
1 | <div class="row"> |
So as you see our table is ItemsTable and has 3 columns. Now we need to add the js code in scripts section.
Let’s see what we’ve got
- Reference to the DataTable library, in this example case I set a reference to DataTable CDN.
- Through ajax call with a POST request to /api/items we are going to request information (if we are RESTful strict, we should use GET Method to get information not POST but I prefer this way to avoid limitations related to form data through the query string, so up to you if you want to use GET).
- In columns we bind the information we want to display so the result from the ajax call should return at least that data (records with itemId, name, description), if you see columns is an array, it contains an object of each column, also you can add a function inside each column in case you want to add more logic (in future post we’ll see it).
- We can specify to sort and page the information we want to display, in that way we will see page buttons and sort icons on each row header.
If you run the app, we’ll only see this
Server Side - API to return data
Creating Api
Let’s add some code to see results in the table. Add a new controller inside an api folder (or whichever the folder you want).
We are going to use post method so let’s remove the auto-generated code.
In the post method we are going to return a custom result so we’re going to change void to IActionResult and return an OK
Initial version
After changes
Let’s add a model class named Item in Models folder
Add 3 properties
Returning Data from the Api
Let’s go back to ItemsController.cs to create a private method to return data (to ease the post we’re not going to do the DB plumbing, in a different post we can work that part).
Let’s create a GetData private method like this one
We are going to return a structure like this
1 | { |
In DataTables documentation you’ll see the required structure (server side documentation - data source and server side documentation)
In our code let’s call the data and return a proper json result
If we run the application we’ll see data in our table
If we consume the API directly (using any api client like postman) we’ll see the json structure
If we click on any button page we will get a kind of never ending “Processing”
Which means we have to add more code to make a proper pagination from the server side
under the hood - form data
If we use the dev tools from the browser, in the network section we’ll see the json request.
Click on the request “items/api” at the left column.
In Headers/Form Data (form data is the information we sent from client to server in the request process) for each column there is information that could help us to paginate our result from the data source
Start : from where it starts to paginate.
Length: number of records per page (we get this one from show entries dropdownlist).
order[0][column]: order column index.
order[0][dir]: ascending or descending order to show the information.
colum[?][data]: name of the column of the data returned by the server.
search[value]: value to search in the collection (we get this one from search field).
When the request occurs, as a client we send data (client side), we are going to get Form data (server side), it has information of the columns, pagination and ordering, all related to the Datatable.
In the Api - Paging, Ordering information
Let’s go to ItemsController.cs to add more code
We get all the form data.
Then we create a method to get the information about ordering and pagination (requestFormData) and query over the information in this case using linq in a collection (lstElements)
Private method
Get property helps us to get a property object model related to a particular column name.
Going back to the Post method now we can have a processed collection (paginated and ordered)
Now in the custom response in Data we are sending the processed collection. In Draw (number of times the datatable plugin has generated the table) we send the value from the form data. In RecordsFiltered and RecordsTotal we are sending the total items from initial collection.
If we run the application we’ll see it working
Pagination works
Ordering works
You can download the source code from the repository.
In a future post we are going to filter using the search field.
Bonus:
From the Guitar Hero Hendrix, a better version than the original (Bob Dylan, song author, endorse it).
Jimi Hendrix - All Along The Watchtower