Home > Software design >  DataTable show Ajax error while return Json in .NET MVC
DataTable show Ajax error while return Json in .NET MVC

Time:10-05

The model works well until I store Date datatype in my SQL Server When I try return Json using ToListAsync(), it shows ajax error. This is the Prog Models

    [Required]
    public string Name { get; set; }

    public string Module { get; set; }

    public string Product { get; set; }

    public string Segment { get; set; }

    public DateTime Date { get; set; }

This is the function in Controller. Bookscontroller is the controller for Prog Model. I just didn't change the name.

    private readonly ApplicationDbContext _db;

    [BindProperty]
    public Prog Prog { get; set; }

    public BooksController(ApplicationDbContext db)
    {
        _db = db;
    }

    #region API Calls
    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        return Json(new { data = await _db.Progs.ToListAsync() });
    }

This is the jquery in javascript using DataTable.

 dataTable = $('#DT_load').DataTable({
    "ajax": {
        "url": "/books/getall/",
        "type": "GET",
        "datatype": "json"
    },
    "columns": [
        {
            "data": "name",
            "render": function (data) {
                return `<div >
                        <a  href=""  style='cursor:pointer; width:80px;'>
                           ${data}
                        </a>
                        
                        </div>`;
            },"width": "20%"
        },
        { "data": "module", "width": "15%" },
        { "data": "product", "width": "15%" },
        { "data": "segment", "width": "15%" },
        { "data": "date", "width": "20%" },

Error shown in browser
Error shown in browser

DataTables warning: table id=DT_load - Ajax error. For more information about this error, please see enter image description here

Example with datetime

enter image description here

Update:

If you want to make DateTime as Nullable then you can do that in database like below:

enter image description here

Besides, In Entity Model, we can deifne a property as nullable by putting ? in it. Like below:

 public DateTime? Date{ get; set; }
  • Related