[Solved]-How to reload DataTables with the latest data fetched from the server using AJAX in ASP.NET MVC


I'm currently working on a project where I'm displaying a list of tourist information in the admin section. I need to update this data periodically so that the admin can see the latest information from the server. To display the list, I'm using a DataTable. Let's discuss step by step how we can refresh or reload a DataTable after making an AJAX call in MVC.

In this post we will cover the following points:

  • How To Reinitialize Datatable in Ajax in ASP.NET MVC
  • How to Refresh or reload a datatable after using ajax call in mvc
Let's take an example of how we can reload dataTables with newly fetched data from the server using AJAX in an MVC application, assuming we're working with a Tourist model with fields such as Id, FullName, Gender, Email, and About, and using Entity Framework.


using System.ComponentModel.DataAnnotations;

public class Tourist
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(100)]
    public string FullName { get; set; }

    [Required]
    public string Gender { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    public string About { get; set; }
}
First, let's start with the controller code:
using System.Linq;
using System.Web.Mvc;
using TestApp.Models; //
public class TouristController : Controller
{
    private DbContext db = new DbContext(); // DbContext name

    public ActionResult Index()
    {
        return View();
    }

    // Action to fetch tourists data
    public ActionResult GetTouristsData()
    {
        var tourists = db.Tourists.ToList();
        return Json(tourists, JsonRequestBehavior.AllowGet);
    }
}
View code:
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Tourist DataTable Example</title>  
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
</head>
<body>

<table id="touristTable" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Id</th>
            <th>Full Name</th>
            <th>Gender</th>
            <th>Email</th>
            <th>About</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<script>
    $(document).ready(function () {
        $('#touristTable').DataTable({
            ajax: {
                url: '@Url.Action("GetTouristsData", "Tourist")', 
                dataSrc: '' // We have set data source to empty because it's directly an array
            },
            columns: [
                { data: 'Id' },
                { data: 'FullName' },
                { data: 'Gender' },
                { data: 'Email' },
                { data: 'About' }
            ]
        });

        // Function to reload dataTables with latest data
        function reloadDataTable() {
            $('#touristTable').DataTable().ajax.reload();
        }

        // calling reloadDataTable function when button clicked
        $('#reloadBtn').click(function () {
            reloadDataTable();
        });
    });
</script>

<button id="reloadBtn">Reload DataTable</button>

</body>
</html>
In above example, in the controller we have an action method GetTouristsData which fetches the tourist data from the database and returns it as JSON. The view page having a DataTable initialized with data array using AJAX. The reloadDataTable function is used to reload the DataTable with latest data from server.
If `$('#touristTable').DataTable().ajax.reload()` doesn't work for you, you can also try: `$('#touristTable').DataTable().clear().destroy();`.
Let's assume that the tourist table also has a column named 'Action' with a delete button. Then, we want to refresh the table when clicking on the delete button. In this example, we are only going to remove the row from the DataTable instead of reloading the complete table.
<script>
    $(document).ready(function () {
        var touristTable = $('#touristTable').DataTable({
            ajax: {
                url: '@Url.Action("GetTouristsData", "Tourist")', 
                dataSrc: '' 
            },
            columns: [
                { data: 'Id' },
                { data: 'FullName' },
                { data: 'Gender' },
                { data: 'Email' },
                { data: 'About' },
                {
                    data: null,
                    render: function (data, type, row) {
                        return '<button class="deleteBtn" data-id="' + data.Id + '">Delete</button>';
                    }
                }
            ]
        });

        // Delete button click event handler
        $('#touristTable').on('click', '.deleteBtn', function () {
            var touristId = $(this).data('id');
            var row = $(this).closest('tr');
            // Make AJAX call to delete tourist by ID
            $.ajax({
                url: '@Url.Action("DeleteTourist", "Tourist")', // Action method to delete tourist
                method: 'POST',
                data: { id: touristId },
                success: function () {
                    // Remove row from DataTable after successful deletion of tourist record
                    touristTable.row(row).remove().draw(false);
                },
                error: function (xhr, status, error) {
                   alert('Unable to delete record');
                }
            });
        });
    });
</script>