如何从ajax数据中选择行

时间:2016-08-20 07:07:31

标签: jquery asp.net-mvc twitter-bootstrap jqgrid free-jqgrid

免费的jqgrid包含每行的按钮。单击按钮进行ajax调用,根据单击的行列值返回客户列表。

用户可以从此数据中选择客户。选定的客户名称和ID应写入jqgrid行。

我试过下面的代码,但我得到了:

  

未捕获的TypeError:无法读取属性' rowIndex'未定义的

此行代码发生此错误:

var clickedId = $(this).closest('tr')[0].rowIndex,

在选择表单中的任何位置点击。

如何解决这个问题?应用程序包含来自不同数据的多个此类选择。哪个是实现它们以避免代码重复的最佳方法?

表是在javascript中创建的。它是否合理/如何使用某些MVC局部视图或其他模板?

此代码可以改进/重构吗?

使用免费的jqgrid 4.13.3-pre,.NET 4.6,ASP.NET MVC,Bootstrap 3,jQuery,jQuery UI。

选择表格从bootstrap模态样本中复制:

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <table class='table table-hover table-striped'>
                    <thead>
                        <tr><td>Customer name</td><td>Customer Id</td></tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">close without selection</button>
            </div>
        </div>
    </div>
</div>

jqgrid colmodel:
    formatter: "showlink",
    formatoptions: {
        onClick: function (options) {
            var nimeosa = getColumnValue('customername', options.rowid);
            if (nimeosa == null) {
                return false;
            }
            $.ajax('api/Customers/FromRegister?' + $.param({ namepart: nimeosa }), {
                type: 'GET',
                dataType: 'json',
                contentType: "application/json",
                async: false
            }).done(function (data, textStatus, jqXHR) {
                var valik = "";
                for (var i = 0; i < data.customerlist.length; i++) {
                    valik += '<tr><td>' + data.customerlist[i].customerName + '</td><td>' +
                        data.customerlist[i].customerId + '</td></tr>';
                }
                $('#exampleModal').on('show.bs.modal', function (event) {
                    $('.modal-body tbody').html(valik);
                });

                $('#exampleModal').on('click.bs.modal', function (event) {
                    // how to fix Uncaught TypeError: Cannot read property 'rowIndex' of undefined in this line:
                    var clickedId = $(this).closest('tr')[0].rowIndex,                                    clickedElem = data.customerlist[clickedId];
                    $('#' + options.rowid + '_customername').val(clickedElem.customerName);
                    $('#' + options.rowid + '_customerid').val(clickedElem.customerId);
                });
                $('#exampleModal').modal();
            );
            return false;
        }
    }

// gets column value from jqgrid row
function getColumnValue(valjaNimi, rowId) {
    var
        iNimi = getColumnIndexByName($grid, valjaNimi),
        $nimi = $('#' + rowId + '>td:nth-child(' + (iNimi + 1) + ')'),
        nimiVal;

    if ($nimi.find('>input').length === 0) {
        // the cell is not in editing mode 
        nimiVal = $nimi.text();
    }
    else {
        nimiVal = $nimi.find('>input').val();
    }

    if (nimiVal === undefined || nimiVal.trim() === '') {
        alert('No value');
        return null;
    }
    return nimiVal;
}

更新

我从答案中尝试了代码。 行比自举模态宽度宽。 宽行变得比形式宽:

enter image description here

如何解决这个问题? 如何强制力行显示在模态内? 如果有多行不适合屏幕,如何创建滚动条?

1 个答案:

答案 0 :(得分:1)

为了从行中获取客户的值,您需要处理<tr>元素的click事件,而不是其父模式。由于行是动态添加的,因此您需要使用事件委派来处理它。

$('#exampleModal tbody').on('click', 'tr', function() {
    var cells = $(this).children('td');
    $('#' + options.rowid + '_customername').val(cells.eq(0).text());
    $('#' + options.rowid + '_customerid').val(cells.eq(1).text());
    $('exampleModal').hide(); // assuming you want to close the modal
});

注意上面应该是一个单独的脚本,但是它不清楚options.rowid是什么,如果它可以存储在全局变量中或传递给模态,那么可以在上面的函数中访问它(参见下面的内容)建议)

作为旁注,你的一些功能似乎没必要(你每次都要重新连接相同的事件),我相信代码可以只是

// declare rowID as a global var and then in the above script you can use
// $('#' + rowID + '_customername').val(cells.eq(0).text());
var rowID;
var table = $('#exampleModal tbody'); // cache it

....
onClick: function (options) {
    rowID = options.rowid; // set the row ID
    ....
    $.ajax('api/Customers/FromRegister?' + $.param({ namepart: nimeosa }), {
        type: 'GET',
        dataType: 'json',
        contentType: "application/json",
        async: false
    }).done(function (data, textStatus, jqXHR) {
        table.empty(); // clear any existing rows
        $.each(data, function(index, item) {
            var row = $('<tr></tr>');
            row.append($('<td></td>').text(item.customerName ));
            row.append($('<td></td>').text(item.customerId));
            table.append(row);
        });
        $('#exampleModal').modal(); // display the mpday
    );
    return false;
}