Search code examples
ajaxdatatablesasp.net-core-mvc.net-5asp.net-core-signalr

C# jQuery Ajax Datatables ASP.NET Core 5 MVC


I am attempting to implement ASP.NET Core SignalR. I am looking for assistance. The project is located at: https://github.com/Talsiter/AspNetCore-SignalR-SqlTableDependency

The issue that I am running into is when a datatable is being populated from jQuery AJAX, no data is being populated into the view.

Items model (Item.cs)

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace InAndOut.Models
{
    public class Item
    {
        [Key]
        public int Id { get; set; }
        public string Borrower { get; set; }
        public string Lender { get; set; }
        [DisplayName("Item name")]
        public string ItemName { get; set; }
    }
}

Items view (Index.cshtml)

@model IEnumerable<InAndOut.Models.Item>

<div class="container p-3">
  <div class="row">
    <div class="col-12">
      <div class="card">
        <div class="card-header">
          <div class="card-body">
            <table id="myTable" class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Id</th>
                  <th>Item Name</th>
                  <th>Borrower</th>
                  <th>Lender</th>
                  <th>Action</th>
                </tr>
              </thead>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

@section Scripts {

  @* These Scrips are Required *@
  <script src="~/js/signalr/dist/browser/signalr.js"></script>

  @*This one gives me an error of "ItemsHub undefined"*@
  @*<script src="~/js/items01.js"></script>*@

  @* This gives me an error "DataTable is not a function"
    This probably requires the *@
  <link href="//cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" rel="stylesheet" />
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>

  <script src="~/js/items03.js"></script>
}

Items JS file (items03.js):

// This is from:
//https://stackoverflow.com/questions/51764211/jquery-datatable-loading-using-ajax-asp-net-mvc
// Does Not Display any data
function getAllMessages() {
  $('#myTable').DataTable({
    processing: true,
    serverSide: false,
    ordering: true,
    paging: true,
    searching: true,
    columns: [
      { title: "Id" },
      { title: "ItemName" },
      { title: "Borrower" },
      { title: "Lender" },
      { title: "View Data" }
    ],
    columns: [
      { data: "Id" },
      { data: "ItemName" },
      { data: "Borrower" },
      { data: "Lender" },
      {
        data: null,
        defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
      }
    ],
    ajax: {
      "url": "/Item/GetItems",
      "type": "GET",
      "dataSrc": ''
    },
    "columnDefs": [
      {
        "targets": 0,
        "visible": false
      }
    ]
  });
}

Item controller (ItemController.cs):

// This was updated from:
// https://stackoverflow.com/questions/51705732/jquery-datatable-ajax-no-data-available-mvc
public IActionResult GetItems()
{
    var items = new List<Item>
         {
             new Item { Id = 1, ItemName = "Computer", Borrower = "Justin", Lender = "Don"},
             new Item { Id = 2, ItemName = "Mouse", Borrower = "Mark", Lender = "Susan"},
             new Item { Id = 3, ItemName = "Monitor", Borrower = "Mark", Lender = "Joe"},
             new Item { Id = 4, ItemName = "Keyboard", Borrower = "Candace", Lender = "Angela"},
             new Item { Id = 5, ItemName = "Printer", Borrower = "Mike", Lender = "Watson"},
         };
      // JsonRequestBehavior requires Microsoft.AspNet.MVC
      // I do not want to reference it. I want to use Microsoft.AspNetCore.Mvc
      //return Json(items, JsonRequestBehavior.AllowGet);

      // I referenced this to mitigate the above issue
      // https://stackoverflow.com/questions/38578463/asp-net-core-the-name-jsonrequestbehavior-does-not-exist-in-the-current-cont
      //return Json(items);
      // Error: Cannot read property 'style' of undefined

      // This was another option
      //return Json(items, new Newtonsoft.Json.JsonSerializerSettings());
      // Error: Cannot read property 'style' of undefined

      // This seems to be returning the correct data format
      // Now the data just is not being displayed in the view
      // My error seems to be in the JavaScript
      return Json(new { data = items });
}

After many attempts, this is about the closest that I am able to get. While debugging the site, I do not receive any errors, but the mock data does not appear in the items view.

I am suspecting that my issue is in the Items JS file in the getAllMessages() method. I am just not sure how to fix it.


Solution

  • The naming convention for response in asp.net core is camel case instead of pascal case. Also you need remove "dataSrc": ''.

    Change like below:

    columns: [
      { data: "id" },
      { data: "itemName" },
      { data: "borrower" },
      { data: "lender" },
      {
        data: null,
        defaultContent: "<button class='tblview'>View Id</button><button class='tblDelete'>Delete</button>"
      }
    ],
    ajax: {
        "url": "/Item/GetItems",
        "type": "GET",
        //"dataSrc": ''
    },