Ad

How To Access A Complex Object Comming From A Datatable Cell In JQuery/Javascript

I have a list of Record objects for the view model (of a Microsoft MVC view) that has the following variables:

Variable1 of string type
Variable2 of int type
... 

I have a razor view for the Record object with a table like the following:

<table id="MyTable">
    <thead>
        <tr>
            <th class="col1" id="Column1">Column1</th>
            <th class="col2" id="Column2">Column2</th>
            <th class="col3" id="Column3">Column3</th>
        </tr>
    </thead>
    <tbody>
        @foreach (Record currentRecord in ListOfRecords)            {
            <tr>
                <td class="col1">X</td>
                <td class="col2">Y</td>
                <td class="col3">@currentRecord</td>
            </tr>
        }
    </tbody>
</table>

Then in my JQuery:

$(document).ready(function () {

    function displayData(datainput) {
        alert(datainput.Variable1)
    }

    var oTable = $('#MyTable').DataTable({
        "oLanguage": { "sSearch": "Search all columns:" },
        "sScrollY": "200px",
        "bPaginate": false
    });

    $('#MyTable tbody').on('click', 'td', function () {
        var rowIndex = oTable.cell(this).index().row;
        var theData = oTable.cell(rowIndex,2).data();
        displayData(theData)
    });
});

the idea is to display Variable1 from the record object of that specific row the user clicked on as an alert text, specifically in that displayData function. But I am unable to get to that variable in the displayData function. the alert displays undefined instead of the value of Variable1. Is there a specific way that I need to pass the parameter? I'm new at JavaScript/JQuery/Razor views so please help if you can.

Thank you.

Ad

Answer

For those that are interested, got it working using Json, first encode it in the view:

<tbody>
    @foreach (Record currentRecord in ListOfRecords)            {
        <tr>
            <td class="col1">X</td>
            <td class="col2">Y</td>
            <td class="col3">@Html.Raw(Json.Encode(currentRecord))</td>
        </tr>
    }
</tbody>

Then parse it in the script:

$('#MyTable tbody').on('click', 'td', function () {
    var rowIndex = oTable.cell(this).index().row;
    var theData = jQuery.parseJSON(oTable.cell(rowIndex,2).data());
    displayData(theData)
});
Ad
source: stackoverflow.com
Ad