Parsing JSON response to datatable
Parsing JSON response to datatable
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:
This discussion has been closed.
            
Answers
I think the
dataparameter for thesuccessfunction is JSON string not Javascript object. Try parsing it to a JS object usingdata = JSON.parse(data);. The rows are in thedataobject which is what theajaxoption expects but since you are using your own you need to change yourdataoption todata: data.data,.Hope this works.
Kevin
Thanks @Kthorngern
do you mean something like this...?
For your original example I meant for the changes:
If you want to use the
ajaxoption then remove thedataoption 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:Either option should work. If you continue to have problems then please post any alert messages or browser console errors you get.
Kevin
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)
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...
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.
Your first example uses jQuery ajax not the Datatables
ajaxoption. Notice it is outside the Datataables init code and uses thesuccessfunction to init Datatables.Your second uses the
ajaxoption but also has thesuccessfunction. This is from theajaxdocs: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