Parsing JSON response to datatable

Parsing JSON response to datatable

singhswatsinghswat Posts: 20Questions: 7Answers: 0

Hi,

... I'm struggling badly with parsing JSOn response to datatable... or Binding JSON response to datatable.

So if I invoke / call my Index method on controller then I get JSON response (as shown below)... I'm not sure what binds Json response to datatable...

Current output

My sample code below...

Controller code

using JQueryDatatablesExample.Models;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;

namespace JQueryDatatablesExample.Controllers
{
    public class ServiceTypesController : Controller
    {
        private mAirFreightPortal db = new mAirFreightPortal();

        // GET: ServiceTypes
        public ActionResult Index()
        {
            //return View(db.ServiceTypes.ToList());
            return  Json(new { data = db.ServiceTypes.ToList() }, JsonRequestBehavior.AllowGet);
        }

View code snippet

@model IEnumerable<JQueryDatatablesExample.Models.ServiceType>

@{
    ViewBag.Title = "Index";
}

@section scripts{

    <script src="~/Scripts/jquery-3.4.1.js"></script>
    <link rel="stylesheet" type="text/css" href="~/Content/DataTables/css/jquery.dataTables.css">
    <script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
    <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //$('#example').DataTable();
            $.ajax({
                "url": "/ServiceType/Index",
                "type": "GET",
                "datatype": 'json',
                "success": function (data) {
                    $('#example').DataTable({
                        data: data,
                        columns: [
                            { 'data': 'ServiceTypeId' },
                            { 'data': 'ServiceTypeCode' },
                            { 'data': 'ServiceTypeDesc' },
                            { 'data': 'CreatedDate' },
                            { 'data': 'CreatedBy' },
                            { 'data': 'ModifiedDate' },
                            { 'data': 'ModifiedBy' },
                        ]
                    });
                }
            });
        });
    </script>
}
<body>
    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>ServiceTypeId</th>
                <th>ServiceTypeCode</th>
                <th>ServiceTypeDesc</th>
                <th>CreatedDate</th>
                <th>CreatedBy</th>
                <th>ModifiedDate</th>
                <th>ModifiedBy</th>
            </tr>
        </thead>
    </table>
</body>

This question has accepted answers - jump to:

Answers

  • kthorngrenkthorngren Posts: 20,276Questions: 26Answers: 4,765
    Answer ✓

    I think the data parameter for the success function is JSON string not Javascript object. Try parsing it to a JS object using data = JSON.parse(data);. The rows are in the data object which is what the ajax option expects but since you are using your own you need to change your data option to data: data.data,.

    Hope this works.

    Kevin

  • singhswatsinghswat Posts: 20Questions: 7Answers: 0
    edited June 2019

    Thanks @Kthorngern

    do you mean something like this...?

    @section scripts{
    
        <script src="~/Scripts/jquery-3.4.1.js"></script>
        <link rel="stylesheet" type="text/css" href="~/Content/DataTables/css/jquery.dataTables.css">
        <script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
        <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#example').DataTable({
                    "ajax": {
                        "url": "/ServiceType/Index",
                        "type": "GET",
                        "datatype": 'json',
                        "data": 'data.data'
                    },
                    columns: [
                        { 'data': 'ServiceTypeId' },
                        { 'data': 'ServiceTypeCode' },
                        { 'data': 'ServiceTypeDesc' },
                        { 'data': 'CreatedDate' },
                        { 'data': 'CreatedBy' },
                        { 'data': 'ModifiedDate' },
                        { 'data': 'ModifiedBy' },
                    ]
                });
            });
        </script>
    }
    <body>
        <table id="example" class="display" style="width:100%">
            <thead>
                <tr>
                    <th>ServiceTypeId</th>
                    <th>ServiceTypeCode</th>
                    <th>ServiceTypeDesc</th>
                    <th>CreatedDate</th>
                    <th>CreatedBy</th>
                    <th>ModifiedDate</th>
                    <th>ModifiedBy</th>
                </tr>
            </thead>
        </table>
    </body>
    
  • kthorngrenkthorngren Posts: 20,276Questions: 26Answers: 4,765
    Answer ✓

    For your original example I meant for the changes:

                $.ajax({
                    "url": "/ServiceType/Index",
                    "type": "GET",
                    "datatype": 'json',
                    "success": function (data) {
    
                        data = JSON.parse(data);  // Parse the JSON string
    
                        $('#example').DataTable({
                            data: data.data,  // Get the data object
                            columns: [
                                { 'data': 'ServiceTypeId' },
                                { 'data': 'ServiceTypeCode' },
                                { 'data': 'ServiceTypeDesc' },
                                { 'data': 'CreatedDate' },
                                { 'data': 'CreatedBy' },
                                { 'data': 'ModifiedDate' },
                                { 'data': 'ModifiedBy' },
                            ]
                        });
                    }
                });
    

    If you want to use the ajax option then remove the data option as that is an ajax option to send data to the server. My guess is this is giving you an error seen in your browser's console. Maybe something like this:

                $('#example').DataTable({
                    "ajax": {
                        "url": "/ServiceType/Index",
                        "type": "GET",   // you can probably remove this
                        "datatype": 'json',   // you can probably remove this
                    },
                    columns: [
                        { 'data': 'ServiceTypeId' },
                        { 'data': 'ServiceTypeCode' },
                        { 'data': 'ServiceTypeDesc' },
                        { 'data': 'CreatedDate' },
                        { 'data': 'CreatedBy' },
                        { 'data': 'ModifiedDate' },
                        { 'data': 'ModifiedBy' },
                    ]
                });
    

    Either option should work. If you continue to have problems then please post any alert messages or browser console errors you get.

    Kevin

  • singhswatsinghswat Posts: 20Questions: 7Answers: 0

    Thanks Kevin

    Still the same output... ( I can see only JSON response not the datatable :( )

    My update code... (I have tried both versions of your code but result is the same)

        <script type="text/javascript">
            alert('Hello');
            $(document).ready(function () {
                debugger;
                alert('world');
                $('#example').DataTable({
                    "ajax": {
                        "url": "/ServiceType/Index",
                        "type": "GET",
                        "datatype": 'json',
                        "success": function (data) {
    
                            data = JSON.parse(data);  // Parse the JSON string
    
                            $('#example').DataTable({
                                data: data.data,  // Get the data object
                                columns: [
                                    { 'data': 'ServiceTypeId' },
                                    { 'data': 'ServiceTypeCode' },
                                    { 'data': 'ServiceTypeDesc' },
                                    { 'data': 'CreatedDate' },
                                    { 'data': 'CreatedBy' },
                                    { 'data': 'ModifiedDate' },
                                    { 'data': 'ModifiedBy' },
                                ]
                            });
                        },
                    }
                });
            });
        </script>
    }
    

    If I press F12 on the chrome borwser then there are no error messages on console...

    Side note... my alert messages of hello world is not getting fired up.

    Output is still the same...

  • singhswatsinghswat Posts: 20Questions: 7Answers: 0

    Okay, I think I understand the problem but I don't know the solution

    Ajax is calling the Controller action method but how can it learn that which view it needs to use to display result...? and this is the reason why it is displaying JSON response... (I guess)

    But what the solution? Any help is highly appreciated.

  • kthorngrenkthorngren Posts: 20,276Questions: 26Answers: 4,765
    edited June 2019 Answer ✓

    Your first example uses jQuery ajax not the Datatables ajax option. Notice it is outside the Datataables init code and uses the success function to init Datatables.

    Your second uses the ajax option but also has the success function. This is from the ajax docs:

    success - Must not be overridden as it is used internally in DataTables. To manipulate / transform the data returned by the server use ajax.dataSrc (above), or use ajax as a function (below).

    You are trying to blend the two options I provided which won't work. The second I provided is a more standard Datatables way to fetch ajax. See if it works for you.

    Kevin

This discussion has been closed.