jquerydatatablesasp.net-core-mvc

How to refresh jquery datatable without database call


In my ASP.NET Core MVC app, I am using a jQuery datatable and it uses Ajax calls to load data from database. The datasource is a List<Student> object.

Now I load the datatable with List<Student> object. And I remove or add any student object to List<Student> in the client side, how I can reflect these changes in the datatable?

After removing 1 or 2 items from the List<Student>, how we can reflect these changes in the datatable without reloading the page again?

I tried with this code:

$('#example').DataTable().ajax.reload(); // nothing happens to datatable

exampletable.ajax.reload(); // nothing happens to datatable

Solution

  • A whole working demo to achieve your requirement for doing database call after client side add/remove operation:

    Model

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
    }
    public class StudentChangesModel
    {
        public List<Student> AddedStudents { get; set; }
        public List<Student> DeletedStudents { get; set; }
    }  
    

    View

    @{
        ViewData["Title"] = "Student Management";
    }
    
    <h1>Student Management</h1>
    
    <!-- Table to display students -->
    <table id="studentsTable" class="display" style="width: 100%;">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Age</th>
                <th>Grade</th>
                <th>Actions</th>
            </tr>
        </thead>
    </table>
    
    <!-- Form to add a new student -->
    <h2>Add New Student</h2>
    <div>
        <label>Name: </label><input type="text" id="nameInput" />
        <label>Age: </label><input type="text" id="ageInput" />
        <label>Grade: </label><input type="text" id="gradeInput" />
        <button id="addStudentBtn">Add Student</button>
    </div>
    
    <!-- Button to save changes -->
    <button id="saveChangesBtn">Save Changes</button>
    
    @section Scripts {
            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
            <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
            <script>
                var addedStudents = [];
                var deletedStudents = [];
    
                $(document).ready(function () {
                    var table = $('#studentsTable').DataTable({
                        ajax: {
                            url: '/Students/GetStudents',
                            dataSrc: ''
                        },
                        columns: [
                            { data: 'id' },
                            { data: 'name' },
                            { data: 'age' },
                            { data: 'grade' },
                            { data: null, defaultContent: '<button class="delete-btn">Delete</button>' }
                        ]
                    });
    
                    // Add new student to the table
                    $('#addStudentBtn').click(function () {
                        var newStudent = {
                            id: 0, // Empty for new student
                            name: $('#nameInput').val(),
                            age: parseInt($('#ageInput').val()),
                            grade: $('#gradeInput').val()
                        };
    
                        // Add the new student to the DataTable
                        table.row.add(newStudent).draw();
    
                        // Track the new student in "addedStudents" array
                        addedStudents.push(newStudent);
    
                        // Clear input fields
                        $('#nameInput').val('');
                        $('#ageInput').val('');
                        $('#gradeInput').val('');
                    });
    
                    // Capture delete button click
                    $('#studentsTable tbody').on('click', 'button.delete-btn', function () {
                        var row = table.row($(this).parents('tr'));
                        var data = row.data();
    
                        // Track removed students only if they exist in DB (have an ID)
                        if (data.id) {
                            deletedStudents.push(data);
                        }
    
                        // Remove the row from DataTable
                        row.remove().draw();
                    });
    
                    // Save changes to the server
                    $('#saveChangesBtn').click(function () {
                        console.log(addedStudents)
                            console.log(deletedStudents)
                        $.ajax({
                            url: '/Students/SaveStudents',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify({
                                addedStudents: addedStudents,
                                deletedStudents: deletedStudents
                            }),
                            success: function (response) {
                                addedStudents = [];
                                deletedStudents = [];
                                alert('Changes saved successfully!');
                                table.ajax.reload();
                            },
                            error: function (error) {
                                console.error('Error saving changes', error);
                            }
                        });
                    });
                });
            </script>
    }
    

    Controller

    public class StudentsController : Controller
    {
        private readonly MvcProjContext _context;
    
        public StudentsController(MvcProjContext context)
        {
            _context = context;
        }
        public IActionResult GetStudents()
        {
            List<Student> students = _context.Student.ToList();
            return Json(students);
        }
        [HttpPost]
        public async Task<IActionResult> SaveStudents([FromBody] StudentChangesModel changes)
        {
            // Process added students
            foreach (var student in changes.AddedStudents)
            {
                _context.Add(student);
            }
    
            // Process deleted students
            foreach (var student in changes.DeletedStudents)
            {
                var data = await _context.Student.FindAsync(student.Id);
    
                _context.Student.Remove(data);
            }
            await _context.SaveChangesAsync();
            return Ok(new { message = "Changes saved successfully!" });
        }
    }