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.

ajax reques to server
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

new project in blank solution

Choose .net core category, select asp.net core web application and give a name

ASP.Net Core Web Application

We select the Web Application Template
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)
JQuery

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 add

1
@RenderSection(“styles”, required: false)

Section styles

At the end of body tag add

1
@RenderSection(“scripts”, required : false)

Section scripts

We are going to navigate through Home/Index view and remove some auto-generated code.
Let’s remove all of this code
home/index view

We are going to have something like this in Home/Index view (or whichever order you want to have)
home/index view structure

Let’s add a reference to the datatable style
Reference in style section

The very basic table structure (installation) we need is something like this one
sample basic html DataTable

In the js side
sample js code to load DataTable
So as you see the table id is very important.

Let’s add the table structure
html DataTable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Items</h3>
</div>
<div class="panel-body">
<table id="ItemsTable" class="table table-striped table-bordered table-hover responsive" width="100%">
<thead class="thin-border-bottom">
<tr>
<th>Item Id</th>
<th>Name</th>
<th>Description</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>

So as you see our table is ItemsTable and has 3 columns. Now we need to add the js code in scripts section.
js code for DataTable

Let’s see what we’ve got
js code for DataTable

  1. Reference to the DataTable library, in this example case I set a reference to DataTable CDN.
  2. 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).
  3. 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).
  4. 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
running the app no data in DataTable

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).
new controller in api folder

items controller

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
post method in controller
After changes
post method in controller

Let’s add a model class named Item in Models folder
add new class

Add 3 properties
add properties to class

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
GetData method

We are going to return a structure like this

1
2
3
4
5
6
7
8
9
{
"draw":1,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
[ 1010,"RYban 12300","Polarized sunglasses"],
[ 1011,"HDMI Cable","Basic hdmi cable 3 feet"]
]
}

In DataTables documentation you’ll see the required structure (server side documentation - data source and server side documentation)
json structure to return to the client

In our code let’s call the data and return a proper json result
return json from Api post method

If we run the application we’ll see data in our table
DataTable shows data

If we consume the API directly (using any api client like postman) we’ll see the json structure
consuming api from postman

If we click on any button page we will get a kind of never ending “Processing”
processing issue
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.
dev tools - form data

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
post method in controller
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)
post method in controller

Private method
ProcessCollection method

GetProperty 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)
post method in controller

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
DataTable works

Pagination works
DataTable pagination works

Ordering works
DataTable 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