将jQuery DataTables中所有页面的复选框值提交到控制器

时间:2019-01-11 12:13:40

标签: jquery datatable

我正在尝试将所有选择复选框的值传递给控制器​​。当我运行代码时,出现以下错误,并且并非所有复选框值都传递给控制器​​

“未捕获的TypeError:无法读取未定义的属性'selected'”

请谁能告诉我我要去哪里

查看代码

<table id="tblBulckTicket" class="table table-condensed table-striped table-hover datatable responsive" >
 <thead>
  <tr>
     <th>
     </th>
     <th>
        @Html.Label("id", "Ticket ID")
     </th>
     <th>
        @Html.Label("subject", "Subject")
     <th>
        @Html.Label("StageName", "Status")
     </th>
  </tr>
 </thead>
  <tbody>
  @foreach (var item in Model)
  {
  <tr>
     <td>
        <input type="checkbox" name="TicketId" id="TicketId" value="@item.Id">                                  
     </td>
     <td>
        <a class="pull-left btn btn-primary btn-xs" href="@Url.Action("Ticket", "Home" , new { id=item.Id})">
        <i class="fas fa-hashtag"></i>
        @Html.DisplayFor(modelItem => item.Id) </a>
     </td>
     <td>
        @Html.DisplayFor(modelItem => item.Subject)
     </td>
     <td>
        @Html.DisplayFor(modelItem => item.StageName)
     </td>
  </tr>
  }

JavaScript代码

    $(document).ready(function () {
        var table =   $('#tblBulckTicket').DataTable({
            "pageLength": 5
        });

        // Handle form submission event 
        $('#formId').on('submit', function (e) {
            var form = this;
            var rows_selected = table.column(0).checkboxes.selected();
            // Iterate over all selected checkboxes
            $.each(rows_selected, function (index, rowId) {
                // Create a hidden element 
                $(form).append(
                    $('<input>')
                        .attr('type', 'hidden')
                        .attr('name', 'TicketId[]')
                        .val(rowId)
                );
            });
              e.preventDefault();
        });  
       }); 

1 个答案:

答案 0 :(得分:0)

在下面的Ourmandave Javascript代码的帮助下

 $(document).ready(function () {
        var table =   $('#tblBulckTicket').DataTable({
            "pageLength": 5
        });
      $('#formId').on('submit', function (e) {
            var form = this;

            // Iterate over all checkboxes in the table
            table.$('input[type="checkbox"]').each(function () {
                // If checkbox doesn't exist in DOM
                if (!$.contains(document, this)) {
                    // If checkbox is checked
                    if (this.checked) {
                        // Create a hidden element 
                        $(form).append(
                            $('<input>')
                                .attr('type', 'hidden')
                                .attr('name', this.name)
                                .val(this.value)
                        );
                    }
                }
            });
        });
      });