如何从JQuery / Javascript中的数据表单元格访问复杂对象

时间:2015-12-16 00:04:12

标签: javascript jquery model-view-controller razor

我有一个视图模型(Microsoft MVC视图)的Record对象列表,它包含以下变量:

Variable1 of string type
Variable2 of int type
... 

我有一个Record对象的剃刀视图,其中包含如下表:

<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>

然后在我的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)
    });
});

这个想法是从用户点击的特定行的记录对象中显示 Variable1 作为警告文本,特别是在 displayData 函数中。但是我无法在displayData函数中找到该变量。警报显示未定义,而不是 Variable1 的值。我需要传递参数的具体方法吗?我是JavaScript / JQuery / Razor视图的新手,所以请尽可能帮忙。

谢谢。

1 个答案:

答案 0 :(得分:0)

对于那些感兴趣的人,让它使用Json工作,首先在视图中对其进行编码:

<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>

然后在脚本中解析它:

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