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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>$('#example').DataTable().ajax.reload(); // nothing happens to datatable
exampletable.ajax.reload(); // nothing happens to datatable
</code>
<code>$('#example').DataTable().ajax.reload(); // nothing happens to datatable exampletable.ajax.reload(); // nothing happens to datatable </code>
$('#example').DataTable().ajax.reload(); // nothing happens to datatable

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

6

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

Model

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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; }
}
</code>
<code>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; } } </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@{
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>
}
</code>
<code>@{ 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> } </code>
@{
    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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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!" });
}
}
</code>
<code>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!" }); } } </code>
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!" });
    }
}

If you’re adding/deleting items in the list from the client side, you should be able to also remove them from the list without the need for a reload. That would be ok from a transactional point of view, until you are sure to make those changes in the underlying data service.

Anyway, you must, somehow, apply those changes in the database before reloading the table from the ajax call. This will also show any external changes to the data on your page.

You can do it, for example, with another ajax call which doesn’t have to update the table immediately.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật