title: Datatables server-side processing in ASP.NET Core 3.1
body: <p>I am new to <strong>Datatables</strong> with AJAX calls. I need to implement server-side processing for thousands of records. I was following a tutorial but I got confused somewhere with server side processing.</p>
  <p>I am getting an error while trying to render the data from the data source. Let me post all the relevant code and hope that you help me identify where I am getting it wrong. Since I am new to <strong>Datatables</strong> and Ajax, I will appreciate more answers with examples, textual answers accompanied by code or link(s) to a tutorial demostrating server side processing in <strong>ASP.NET CORE 3.1</strong>.</p>
  <p>I appreciate your time and help.</p>
  <p>NB. I took the implementation and configurations from a tutorial and tried to customize it.</p>
  <p><strong>Below is the HTML table and its model:</strong></p>
  <pre><code>@model IEnumerable&lt;StudentApplications&gt;
  &lt;table id=&quot;custom-datatable&quot; class=&quot;mb-5 display table table-bordered&quot; style=&quot;width:100%&quot;&gt;
                  &lt;thead&gt;
                      &lt;tr&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.ApplicationId)
                          &lt;/th&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.Firstname)
                          &lt;/th&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.Surname)
                          &lt;/th&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.ApplicationFor)
                          &lt;/th&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.SubmissionDate)
                          &lt;/th&gt;
                          &lt;th&gt;&lt;/th&gt;
                      &lt;/tr&gt;
                  &lt;/thead&gt;
                  &lt;tfoot&gt;
                      &lt;tr&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.ApplicationId)
                          &lt;/th&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.Firstname)
                          &lt;/th&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.Surname)
                          &lt;/th&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.ApplicationFor)
                          &lt;/th&gt;
                          &lt;th&gt;
                              @Html.DisplayNameFor(model =&gt; model.SubmissionDate)
                          &lt;/th&gt;
                          &lt;th&gt;&lt;/th&gt;
                      &lt;/tr&gt;
                  &lt;/tfoot&gt;
              &lt;/table&gt;
  </code></pre>
  <p><strong>Below is the javascript file initialising an HTML table to datatable and some configurations:</strong></p>
  <pre><code>$(document).ready(function () {
      $('#custom-datatable').DataTable({
  
          // Design Assets
          stateSave: true,
          autoWidth: true,
          // ServerSide Setups
          processing: true,
          serverSide: true,
          // Paging Setups
          paging: true,
          // Searching Setups
          searching: { regex: true },
          // Ajax Filter
          ajax: {
              url: &quot;/myapplications/data&quot;,
              type: &quot;POST&quot;,
              contentType: &quot;application/json&quot;,
              dataType: &quot;json&quot;,
              data: function (d) {
                  return JSON.stringify(d);
              }
          },
          // Columns Setups
          columns: [
              { data: &quot;ApplicationId&quot; },
              { data: &quot;Firstname&quot; },
              { data: &quot;Surname&quot; },
              { data: &quot;ApplicationFor&quot; },
              { data: &quot;SubmissionDate&quot; }
  
              //// For Student.Id
              //{ &quot;data&quot;: &quot;applicationId&quot;, &quot;name&quot;: &quot;ApplicationId&quot; },
              //// For Student.Firstname
              //{ &quot;data&quot;: &quot;firstname&quot;, &quot;name&quot;: &quot;Firstname&quot; },
              //// For Student.Surname
              //{ &quot;data&quot;: &quot;surname&quot;, &quot;name&quot;: &quot;Surname&quot; },
              //// For Student.ApplicationFor
              //{ &quot;data&quot;: &quot;applicationFor&quot;, &quot;name&quot;: &quot;ApplicationFor&quot; },
              //// For Student.SubmissionDate
              //{ &quot;data&quot;: &quot;submissionDate&quot;, &quot;name&quot;: &quot;SubmissionDate&quot; }
          ],
          // Column Definitions
          columnDefs: [
              { targets: &quot;no-sort&quot;, orderable: false },
              { targets: &quot;no-search&quot;, searchable: false },
              {
                  targets: &quot;trim&quot;,
                  render: function (data, type, full, meta) {
                      if (type === &quot;display&quot;) {
                          data = strtrunc(data, 10);
                      }
  
                      return data;
                  }
              },
              { targets: &quot;date-type&quot;, type: &quot;date-eu&quot; },
              {
                  targets: 10,
                  data: null,
                  orderable: false
              },
          ]
      });
  
  });
  </code></pre>
  <p><strong>Below is the method that gets the data:</strong></p>
  <pre><code>// loading datatable
          [HttpPost]
          [Route(&quot;myapplications/data&quot;)]
          public async Task&lt;IActionResult&gt; Data([FromBody] DtParameters dtParameters)
          { 
              searchBy = dtParameters.Search?.Value;
  
              // if we have an empty search then just order the results by Id ascending
              var orderCriteria = &quot;ApplicationId&quot;;
              var orderAscendingDirection = true;
  
              if (dtParameters.Order != null)
              {
                  // in this example we just default sort on the 1st column
                  orderCriteria = dtParameters.Columns[dtParameters.Order[0].Column].Data;
                  orderAscendingDirection = dtParameters.Order[0].Dir.ToString().ToLower() == &quot;asc&quot;;
              }
  
              var result = context.AspNetStudentApplications.AsQueryable();
  
              if (!string.IsNullOrEmpty(searchBy))
              {
                  result = result.Where(r =&gt; r.ApplicationId != null &amp;&amp; r.ApplicationId.ToUpper().Contains(searchBy.ToUpper()) ||
                                             r.Firstname != null &amp;&amp; r.Firstname.ToUpper().Contains(searchBy.ToUpper()) ||
                                             r.Surname != null &amp;&amp; r.Surname.ToUpper().Contains(searchBy.ToUpper()) ||
                                             r.ApplicationFor != null &amp;&amp; r.ApplicationFor.ToUpper().Contains(searchBy.ToUpper()) ||
                                             r.SubmissionDate != null &amp;&amp; r.SubmissionDate.ToUpper().Contains(searchBy.ToUpper()));
              }
  
              result = orderAscendingDirection ? result.OrderByDynamic(orderCriteria, DtOrderDir.Asc) : result.OrderByDynamic(orderCriteria, DtOrderDir.Desc);
  
              // now just get the count of items (without the skip and take) - eg how many could be returned with filtering
              var filteredResultsCount = await result.CountAsync();
              var totalResultsCount = await context.AspNetStudentApplications.CountAsync();
  
              return Json(new DtResult&lt;StudentApplications&gt;
              {
                  Draw = dtParameters.Draw,
                  RecordsTotal = totalResultsCount,
                  RecordsFiltered = filteredResultsCount,
                  Data = await result
                      .Skip(dtParameters.Start)
                      .Take(dtParameters.Length)
                      .ToListAsync()
              });
          }
  </code></pre>
  <p><strong>Below is the DtParameters class and other classes related to Datatables:</strong></p>
  <pre><code>/// &lt;summary&gt;
  /// A full result, as understood by jQuery DataTables.
  /// &lt;/summary&gt;
  /// &lt;typeparam name=&quot;T&quot;&gt;The data type of each row.&lt;/typeparam&gt;
  public class DtResult&lt;T&gt;
  {
      /// &lt;summary&gt;
      /// The draw counter that this object is a response to - from the draw parameter sent as part of the data request.
      /// Note that it is strongly recommended for security reasons that you cast this parameter to an integer, rather than simply echoing back to the client what it sent in the draw parameter, in order to prevent Cross Site Scripting (XSS) attacks.
      /// &lt;/summary&gt;
      [JsonProperty(&quot;draw&quot;)]
      public int Draw { get; set; }
  
      /// &lt;summary&gt;
      /// Total records, before filtering (i.e. the total number of records in the database)
      /// &lt;/summary&gt;
      [JsonProperty(&quot;recordsTotal&quot;)]
      public int RecordsTotal { get; set; }
  
      /// &lt;summary&gt;
      /// Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned for this page of data).
      /// &lt;/summary&gt;
      [JsonProperty(&quot;recordsFiltered&quot;)]
      public int RecordsFiltered { get; set; }
  
      /// &lt;summary&gt;
      /// The data to be displayed in the table.
      /// This is an array of data source objects, one for each row, which will be used by DataTables.
      /// Note that this parameter's name can be changed using the ajax option's dataSrc property.
      /// &lt;/summary&gt;
      [JsonProperty(&quot;data&quot;)]
      public IEnumerable&lt;T&gt; Data { get; set; }
  
      /// &lt;summary&gt;
      /// Optional: If an error occurs during the running of the server-side processing script, you can inform the user of this error by passing back the error message to be displayed using this parameter.
      /// Do not include if there is no error.
      /// &lt;/summary&gt;
      [JsonProperty(&quot;error&quot;, NullValueHandling = NullValueHandling.Ignore)]
      public string Error { get; set; }
  
      public string PartialView { get; set; }
  }
  
  /// &lt;summary&gt;
  /// The additional columns that you can send to jQuery DataTables for automatic processing.
  /// &lt;/summary&gt;
  public abstract class DtRow
  {
      /// &lt;summary&gt;
      /// Set the ID property of the dt-tag tr node to this value
      /// &lt;/summary&gt;
      [JsonProperty(&quot;DT_RowId&quot;)]
      public virtual string DtRowId =&gt; null;
  
      /// &lt;summary&gt;
      /// Add this class to the dt-tag tr node
      /// &lt;/summary&gt;
      [JsonProperty(&quot;DT_RowClass&quot;)]
      public virtual string DtRowClass =&gt; null;
  
      /// &lt;summary&gt;
      /// Add the data contained in the object to the row using the jQuery data() method to set the data, which can also then be used for later retrieval (for example on a click event).
      /// &lt;/summary&gt;
      [JsonProperty(&quot;DT_RowData&quot;)]
      public virtual object DtRowData =&gt; null;
  
      /// &lt;summary&gt;
      /// Add the data contained in the object to the row dt-tag tr node as attributes.
      /// The object keys are used as the attribute keys and the values as the corresponding attribute values.
      /// This is performed using using the jQuery param() method.
      /// Please note that this option requires DataTables 1.10.5 or newer.
      /// &lt;/summary&gt;
      [JsonProperty(&quot;DT_RowAttr&quot;)]
      public virtual object DtRowAttr =&gt; null;
  }
  
  /// &lt;summary&gt;
  /// The parameters sent by jQuery DataTables in AJAX queries.
  /// &lt;/summary&gt;
  public class DtParameters
  {
      /// &lt;summary&gt;
      /// Draw counter.
      /// This is used by DataTables to ensure that the Ajax returns from server-side processing requests are drawn in sequence by DataTables (Ajax requests are asynchronous and thus can return out of sequence).
      /// This is used as part of the draw return parameter (see below).
      /// &lt;/summary&gt;
      public int Draw { get; set; }
  
      /// &lt;summary&gt;
      /// An array defining all columns in the table.
      /// &lt;/summary&gt;
      public DtColumn[] Columns { get; set; }
  
      /// &lt;summary&gt;
      /// An array defining how many columns are being ordering upon - i.e. if the array length is 1, then a single column sort is being performed, otherwise a multi-column sort is being performed.
      /// &lt;/summary&gt;
      public DtOrder[] Order { get; set; }
  
      /// &lt;summary&gt;
      /// Paging first record indicator.
      /// This is the start point in the current data set (0 index based - i.e. 0 is the first record).
      /// &lt;/summary&gt;
      public int Start { get; set; }
  
      /// &lt;summary&gt;
      /// Number of records that the table can display in the current draw.
      /// It is expected that the number of records returned will be equal to this number, unless the server has fewer records to return.
      /// Note that this can be -1 to indicate that all records should be returned (although that negates any benefits of server-side processing!)
      /// &lt;/summary&gt;
      public int Length { get; set; }
  
      /// &lt;summary&gt;
      /// Global search value. To be applied to all columns which have searchable as true.
      /// &lt;/summary&gt;
      public DtSearch Search { get; set; }
  
      /// &lt;summary&gt;
      /// Custom column that is used to further sort on the first Order column.
      /// &lt;/summary&gt;
      public string SortOrder =&gt; Columns != null &amp;&amp; Order != null &amp;&amp; Order.Length &gt; 0
          ? (Columns[Order[0].Column].Data +
             (Order[0].Dir == DtOrderDir.Desc ? &quot; &quot; + Order[0].Dir : string.Empty))
          : null;
  
      /// &lt;summary&gt;
      /// For Posting Additional Parameters to Server
      /// &lt;/summary&gt;
      public IEnumerable&lt;string&gt; AdditionalValues { get; set; }
  
  }
  
  /// &lt;summary&gt;
  /// A jQuery DataTables column.
  /// &lt;/summary&gt;
  public class DtColumn
  {
      /// &lt;summary&gt;
      /// Column's data source, as defined by columns.data.
      /// &lt;/summary&gt;
      public string Data { get; set; }
  
      /// &lt;summary&gt;
      /// Column's name, as defined by columns.name.
      /// &lt;/summary&gt;
      public string Name { get; set; }
  
      /// &lt;summary&gt;
      /// Flag to indicate if this column is searchable (true) or not (false). This is controlled by columns.searchable.
      /// &lt;/summary&gt;
      public bool Searchable { get; set; }
  
      /// &lt;summary&gt;
      /// Flag to indicate if this column is orderable (true) or not (false). This is controlled by columns.orderable.
      /// &lt;/summary&gt;
      public bool Orderable { get; set; }
  
      /// &lt;summary&gt;
      /// Search value to apply to this specific column.
      /// &lt;/summary&gt;
      public DtSearch Search { get; set; }
  }
  
  /// &lt;summary&gt;
  /// An order, as sent by jQuery DataTables when doing AJAX queries.
  /// &lt;/summary&gt;
  public class DtOrder
  {
      /// &lt;summary&gt;
      /// Column to which ordering should be applied.
      /// This is an index reference to the columns array of information that is also submitted to the server.
      /// &lt;/summary&gt;
      public int Column { get; set; }
  
      /// &lt;summary&gt;
      /// Ordering direction for this column.
      /// It will be dt-string asc or dt-string desc to indicate ascending ordering or descending ordering, respectively.
      /// &lt;/summary&gt;
      public DtOrderDir Dir { get; set; }
  }
  
  /// &lt;summary&gt;
  /// Sort orders of jQuery DataTables.
  /// &lt;/summary&gt;
  public enum DtOrderDir
  {
      Asc,
      Desc
  }
  
  /// &lt;summary&gt;
  /// A search, as sent by jQuery DataTables when doing AJAX queries.
  /// &lt;/summary&gt;
  public class DtSearch
  {
      /// &lt;summary&gt;
      /// Global search value. To be applied to all columns which have searchable as true.
      /// &lt;/summary&gt;
      public string Value { get; set; }
  
      /// &lt;summary&gt;
      /// true if the global filter should be treated as a regular expression for advanced searching, false otherwise.
      /// Note that normally server-side processing scripts will not perform regular expression searching for performance reasons on large data sets, but it is technically possible and at the discretion of your script.
      /// &lt;/summary&gt;
      public bool Regex { get; set; }
  }
  </code></pre>
  <p><strong>Here is my empty Table:</strong>
  <a href="https://i.stack.imgur.com/VVqJV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VVqJV.png" alt="Basic Datatable features have been applied" /></a></p>
  <p><strong>Below is the error I am getting while trying to load the data:</strong>
  <a href="https://i.stack.imgur.com/W1L4f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W1L4f.png" alt="This is the error I am getting when trying to load data" /></a></p>
  <p><strong>Where am I getting it wrong?</strong></p>
  <p><strong>Here is where the exception is occuring:</strong>
  <a href="https://i.stack.imgur.com/1s9oG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1s9oG.png" alt="enter image description here" /></a></p>
  <p><strong>@HMZ Implementation, I see empty records (images below):</strong></p>
  <p>I see this alert
  <a href="https://i.stack.imgur.com/a8Ssm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a8Ssm.png" alt="The Alert" /></a></p>
  <p><strong>Stuck on processing</strong>
  <a href="https://i.stack.imgur.com/sOgja.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sOgja.png" alt="Stuck on processing" /></a></p>
  <p><strong>when number of rows is changed, I see this empty table:</strong>
  <a href="https://i.stack.imgur.com/T0SAF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T0SAF.png" alt="Empty table" /></a></p>