Search code examples
jsonbootstrap-table

Table not populated from json data in variable


I am using BoostrapTable in an MVC application. The controller is returning some data as follows:

model.DataAsJson = JsonConvert.SerializeObject(model.Entities.Select(x => x.DataProperties));

My client side looks like this (snippet):

<table id="table"></table>

<script type="text/javascript">
$('#table').bootstrapTable({
    data: '@Model.DataAsJson',
    //url: 'ms.json', 
    columns: [{
        field: 'ClientFileNo',
        title: 'Case No'
    }, {
        field: 'ClientName',
        title: 'Customer Name'
    }]
});

The resulting Json looks like this:

[{
    "RowNum": "2",
    "ID": "XXX",
    "ClientFileNo": "XXX",
    "Description": "XXX",
    "ClientName": "XXX",
    "TypeDescription": "XXX",
    "PrincipleName": "XXX",
    "Created": "2017-11-08T10:31:23.673Z"
  },
  {
    "RowNum": "3",
    "ID": "XXX",
    "ClientFileNo": "XXX",
    "Description": "XXX",
    "ClientName": "XXX",
    "TypeDescription": "XXX",
    "PrincipleName": "XXX",
    "Created": "2017-11-01T12:29:08.763Z"
  }
]

If I paste the result of the SerializeObject() call into a json file and pass to the url property, the table populates as expected. However, if I use the data property and @Model.DataAsJson then I have thousands of empty rows in my table with a '-' in each column.

I have seen a reference to the responseHandler property and I have tried providing a name to my JSON array as follows however it has not fixed my issue:

model.DataAsJson = JsonConvert.SerializeObject(new
        {
            jsonData = model.Entities.Select(x => x.DataProperties)
        });

<script type="text/javascript">
$('#table').bootstrapTable({
    data: '@Model.DataAsJson',
    responseHandler: function (res) {
        res.jsonData
    },

Can anyone see why this would happen?


Solution

  • Ok got to the bottom of this in case someone else gets caught by it.

    I modified the js to read the model data as following:

    $('#table').bootstrapTable({
    data: @Html.Raw(Model.DataAsJson)
    

    So I removed the apostrophes and added the Html.Raw. I realised this by viewing the data in Chrome debugger and could see it was encoded. Also, I was having some further issues as the legacy codebase I am working with had the script in a partial view and the Chrome debugger was not hitting the debug points. I sorted this by adding:

    debugger;
    

    where I wanted it to break.

    Thanks and hope this helps others.