BapsM BapsM - 4 months ago 212
Javascript Question

Datatable not returning rowid to asp.net mvc controller on form submit

Am unable to get the rowids from the jquery datatable to my controller on form submit.

Please find below the html code:

<form id="frm-example" action="@Url.Action("Index", "Home")" method="POST">

<table id="example" class="display select" cellspacing="0" width="100%">
<thead>
<tr>
<th><input name="select_all" value="1" type="checkbox"></th>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
</table>
<hr>
<p>
<input type="button" value="Add" class="btn btn-success" onclick="location.href='@Url.Action("Create", "UserProfile")'" />
<button type="submit" id="frm-example" class="btn btn-danger" value="Delete">Delete</button>

</p>
<pre id="example-console">
</pre>
</form>


Please find below of my code for Datatable

@* Load datatable css *@
<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
@* Load datatable js *@
@section Scripts{
<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script>

//
// Updates "Select all" control in a data table
//
function updateDataTableSelectAllCtrl(table) {
var $table = table.table().node();
var $chkbox_all = $('tbody input[type="checkbox"]', $table);
var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0);

// If none of the checkboxes are checked
if ($chkbox_checked.length === 0) {
chkbox_select_all.checked = false;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}

// If all of the checkboxes are checked
} else if ($chkbox_checked.length === $chkbox_all.length) {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}

// If some of the checkboxes are checked
} else {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = true;
}
}
}

$(document).ready(function () {
// Array holding selected row IDs
var rows_selected = [];
var table = $('#example').DataTable({
'ajax': '/UserProfile/LoadData',
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'width': '1%',
'className': 'dt-body-center',
'render': function (data, type, full, meta) {
return '<input type="checkbox">';
}
}],
'order': [1, 'asc'],
'rowCallback': function (row, data, dataIndex) {
// Get row ID
var rowId = data['USER_ID'];

// If row ID is in the list of selected row IDs
if ($.inArray(rowId, rows_selected) !== -1) {
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
}, 'columns': [
{ "data": "DT_RowId", "autoWidth": true },
{ "data": "USER_ID", "autoWidth": true },
{ "data": "USER_NAME", "autoWidth": true }
]
});

// Handle click on checkbox
$('#example tbody').on('click', 'input[type="checkbox"]', function (e) {
var $row = $(this).closest('tr');

// Get row data
var data = table.row($row).data();

// Get row ID
var rowId = data['USER_ID'];

// Determine whether row ID is in the list of selected row IDs
var index = $.inArray(rowId, rows_selected);

// If checkbox is checked and row ID is not in list of selected row IDs
if (this.checked && index === -1) {
rows_selected.push(rowId);

// Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
} else if (!this.checked && index !== -1) {
rows_selected.splice(index, 1);
}

if (this.checked) {
$row.addClass('selected');
} else {
$row.removeClass('selected');
}

// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);

// Prevent click event from propagating to parent
e.stopPropagation();
});

// Handle click on table cells with checkboxes
$('#example').on('click', 'tbody td, thead th:first-child', function (e) {
$(this).parent().find('input[type="checkbox"]').trigger('click');
});

// Handle click on "Select all" control
$('thead input[name="select_all"]', table.table().container()).on('click', function (e) {
if (this.checked) {
$('#example tbody input[type="checkbox"]:not(:checked)').trigger('click');
} else {
$('#example tbody input[type="checkbox"]:checked').trigger('click');
}

// Prevent click event from propagating to parent
e.stopPropagation();
});

// Handle table draw event
table.on('draw', function () {
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
});

// Handle form submission event
$('#frm-example').on('submit', function (e) {
var form = this;

// Iterate over all selected checkboxes
$.each(rows_selected, function (index, rowId) {
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});

});


});
</script>
}


Please find below my code in controller.

namespace DOSApplication.Controllers
{

public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}


[HttpPost]
public ActionResult Index(string[] id)
{


return View("Index");
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";

return View();
}

public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";

return View();
}
}
}


The value in the Index action of home controller is showing null.

Answer
  // Handle form submission event 
  $('#frm-example').on('submit', function (e) {
      var form = this;
            console.log('ids: ', rows_selected)
      $.ajax({
        type: 'post',
        url: '',
        data: {
          id:JSON.stringify(rows_selected)
        },
        success: function (response) {
          console.log("You data will be saved, resposnse: ", response);
        }
      });
      return false
  });
Comments