How can we refresh a table using AJAX in ASP.NET MVC?


Suppose we have task to update a table in MVC using AJAX. After inserting, updating, or deleting a row, we want to refresh the table to reflect the changes.

To refresh a table periodically using AJAX in ASP.NET MVC with Entity Framework, considering a Customer model with fields Id, CustomerName, CustomerAddress, and Contact, you can follow these steps:

Create the Customer Model: Define the Customer model with the required fields.
public class Customer
{
    public int Id { get; set; }
    public string CustomerName { get; set; }
    public string CustomerAddress { get; set; }
    public string Contact { get; set; }
}
Create Controller: Implement actions in the controller to handle HTTP requests and retrieve customer data from the database.
public class CustomerController : Controller
{
    private readonly DbContext _context;

    public CustomerController(DbContext context)
    {
        _context = context;
    }

    // Action to return the partial view with the customer table
    public IActionResult GetCustomerTable()
    {
        // Retrieve the list of customers from the database
        List<Customer> customers = _context.Customers.ToList();
        return PartialView("_CustomerTable", customers);
    }
}
Create the Partial View: Develop a partial view (_CustomerTable.cshtml) to display the customer table.
@model List<Customer>

<table id="customerTable">
    <thead>
        <tr>
            <th>Id</th>
            <th>Customer Name</th>
            <th>Customer Address</th>
            <th>Contact</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var customer in Model)
        {
            <tr>
                <td>@customer.Id</td>
                <td>@customer.CustomerName</td>
                <td>@customer.CustomerAddress</td>
                <td>@customer.Contact</td>
            </tr>
        }
    </tbody>
</table>
Use AJAX to Refresh Table Periodically: Add JavaScript/jQuery code to refresh the table using AJAX periodically.
// Function to refresh the customer table using AJAX
function refreshCustomerTable() {
    $.ajax({
        url: '/Customer/GetCustomerTable',
        type: 'GET',
        success: function (data) {
            $('#customerTable').html(data);
        },
        error: function (xhr, status, error) {
            console.error(error);
        }
    });
}

// Call the refreshCustomerTable function every 10 seconds (for example)
$(document).ready(function () {
    refreshCustomerTable();
    setInterval(refreshCustomerTable, 10000); // 10000 milliseconds = 10 seconds
});
Now the customer table will be refreshed periodically using AJAX in ASP.NET MVC with Entity Framework. Adjust the interval in the setInterval function as needed to update the data at the desired frequency.