Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

how-to-return-additional-data-from-the-server-to-client-jquery-datatable-asp.net

Returning Additional Data from the Server to Client in jQuery DataTables

When you required returning additional data from the server to the client, you may need more than the standard fields.

When working with jQuery DataTables and returning additional data from the server to the client, you may need more than the standard fields like draw, recordsTotal, and data. By customizing your server response, you can send additional information—such as status messages or calculated statistics—to enhance the client-side experience. In this guide, we’ll explore how to implement this in an ASP.NET Core MVC setup using a simple in-memory list of employee records.

Setting Up the ASP.NET Core MVC Project

Start by creating a new ASP.NET Core MVC project in Visual Studio. Add the necessary packages for setting up jQuery DataTables in your project.

Creating the Employee Model

Define a simple Employee model with properties such as Id, Name, Position, and Salary.

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Position { get; set; }
    public string Salary { get; set; }
}

Creating an In-Memory List of Employee Records

In your controller, create a list of 15 employee records. For this example, I’ll use a hard-coded list in the EmployeeController.

public class EmployeeController : Controller
{
    private readonly List<Employee> _employees = new List<Employee>
    {
      new Employee { Id = 1, Name = "John Doe", Position = "Software Engineer", Salary = "$100,000" },
    new Employee { Id = 2, Name = "Jane Smith", Position = "Project Manager", Salary = "$120,000" },
    new Employee { Id = 3, Name = "Robert Brown", Position = "Quality Analyst", Salary = "$85,000" },
    new Employee { Id = 4, Name = "Lucy Green", Position = "UX Designer", Salary = "$90,000" },
    new Employee { Id = 5, Name = "Michael White", Position = "Data Scientist", Salary = "$150,000" },
    new Employee { Id = 6, Name = "Sarah Black", Position = "HR Specialist", Salary = "$70,000" },
    new Employee { Id = 7, Name = "Tom Orange", Position = "DevOps Engineer", Salary = "$110,000" },
    new Employee { Id = 8, Name = "Emma Blue", Position = "Backend Developer", Salary = "$95,000" },
    new Employee { Id = 9, Name = "Liam Purple", Position = "Frontend Developer", Salary = "$92,000" },
    new Employee { Id = 10, Name = "Olivia Grey", Position = "Full Stack Developer", Salary = "$130,000" },
    new Employee { Id = 11, Name = "Noah Silver", Position = "Database Administrator", Salary = "$115,000" },
    new Employee { Id = 12, Name = "Ava Gold", Position = "Product Owner", Salary = "$125,000" },
    new Employee { Id = 13, Name = "Mason Yellow", Position = "Scrum Master", Salary = "$105,000" },
    new Employee { Id = 14, Name = "Isabella Red", Position = "Marketing Specialist", Salary = "$80,000" },
    new Employee { Id = 15, Name = "Sophia Violet", Position = "Customer Success Manager", Salary = "$78,000" }
    };

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

    [HttpPost]
    public IActionResult GetEmployees()
    {
        // Additional data
        string statusMessage = "Data loaded successfully";
        string totalSalaries = "$1,500,000";

        return Json(new
        {
            draw = 1,
            recordsTotal = _employees.Count,
            recordsFiltered = _employees.Count,
            data = _employees,
            statusMessage = statusMessage,
            totalSalaries = totalSalaries
        });
    }
}

The GetEmployees action simulates returning data from a server with additional fields, such as statusMessage and totalSalaries.

Creating the View

In Views/Employee/Index.cshtml, set up the HTML structure and include jQuery DataTables initialization:

@{
    ViewData["Title"] = "Employee List";
}

<div id="infoPanel">
    <p>Status: <span id="statusMessage"></span></p>
    <p>Total Salaries: <span id="totalSalaries"></span></p>
</div>

<table id="employeeTable" class="display" style="width:100%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Position</th>
            <th>Salary</th>
        </tr>
    </thead>
</table>

@section Scripts {
    <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#employeeTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '@Url.Action("GetEmployees", "Employee")',
                    type: 'POST',
                    dataSrc: function (json) {
                        // Display additional data
                        $('#statusMessage').text(json.statusMessage);
                        $('#totalSalaries').text(json.totalSalaries);

                        // Return the `data` array to populate the table
                        return json.data;
                    }
                },
                columns: [
                    { data: 'id' },
                    { data: 'name' },
                    { data: 'position' },
                    { data: 'salary' }
                ]
            });
        });
    </script>
}

Configuring the Controller to Return the Draw Parameter

In the GetEmployees action, modify the response to include the draw parameter from the request. This is necessary to keep the DataTables’ state in sync with server responses.

Update the GetEmployees action as follows:

[HttpPost]
public IActionResult GetEmployees([FromForm] int draw)
{
    string statusMessage = "Data loaded successfully";
    string totalSalaries = "$1,500,000";

    return Json(new
    {
        draw = draw,
        recordsTotal = _employees.Count,
        recordsFiltered = _employees.Count,
        data = _employees,
        statusMessage = statusMessage,
        totalSalaries = totalSalaries
    });
}

Testing the Application

Run the application, and navigate to the Employee controller’s Index view. The DataTable should display the employee records, and the additional information (statusMessage and totalSalaries) will appear in the infoPanel section above the table.

Summary

This example demonstrates how to:

  • Set up a basic server-side DataTable using ASP.NET Core MVC.
  • Return additional data from the server, such as statusMessage and totalSalaries.
  • Display this data in the client view using jQuery DataTables.

This approach is a flexible way to manage additional server data, and can easily be adapted to other use cases where you need more data from the server in addition to the default DataTables properties.