If you want to perform sorting of an HTML table by clicking on the column names then you can use jQuery plugin called sortable.js. You can use this plugin without actually downloading or adding it to your website, as you can reference it on the script tag. Once you apply the sorting.js to your HTML table, the HTML table will look like as shown below.
You just need to follow the following 4 steps as outlined below.
Step 1. Add the plugin CSS on the page Head
In your web page’s head section add the following CSS reference.
<link rel="stylesheet" type="text/css" href="https://rern.github.io/sortable/css/sortable.css">
Step 2. Create an HTML table on your web page
The HTML table code.
<table id="tableid">
<thead>
<tr><th>Total Gross</th><th>Change</th><th># Movies</th><th>#1 Movie</th><th>Week</th></tr>
</thead>
<tbody>
<tr>
<td>-$62,930,094</td>
<td>24.9%</td>
<td>13</td>
<td>The Great Wall</td>
<td>-53</td>
</tr>
<tr>
<td>-$50,587,136</td>
<td>-18.6%</td>
<td>10</td>
<td>Passengers (2016)</td>
<td>52</td>
</tr>
<tr>
<td>$61,908,379</td>
<td>27.6%</td>
<td>11</td>
<td>Rogue One: A Star Wars Story</td>
<td>51</td>
</tr>
<tr>
<td>$48,287,470</td>
<td>9.3%</td>
<td>13</td>
<td>Underworld: Blood Wars</td>
<td>50</td>
</tr>
<tr>
<td>$44,172,230</td>
<td>-13.2%</td>
<td>11</td>
<td>Moana</td>
<td>49</td>
</tr>
<tr>
<td>$50,846,288</td>
<td>-39.3%</td>
<td>10</td>
<td>Fantastic Beasts and Where To Find Them</td>
<td>48</td>
</tr>
<tr>
<td>$83,589,429</td>
<td>68.3%</td>
<td>8</td>
<td>Fantastic Beasts and Where To Find Them</td>
<td>47</td>
</tr>
</tbody>
</table>
In a dynamic website build on .NET, you can Read the Records from Entity Framework Core and then display them to the HTML Table. The sortable feature should work correctly.
STEP 3. Add jQuery the sortable.js script on the web page
Add the following 2 script tags in your page. You can add them inside the page head or just before where you end the body tag.
<script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
<script src="https://rern.github.io/sortable/js/sortable.js"></script>
STEP 4. Call the .sortable() function
Add another script tag and make the document.ready() method. Inside it call the .sortable() method on the table’s id like shown below.
<script>
$(document).ready(function () {
$('#tableid').sortable({
});
});
</script>
Conclusion
I hope you liked this quick technique to create sorting feature in your HTML table. Use it whenever there is a requirement in your website. Don’t forget to show your support by clapping a few times for this tutorial.
Check my related tutorial on jQuery - Delete records from GridView without Page Reload using jQuery