Im binding my Data in View to Controller, so later I could do what I want with the data. In my View, im using dataTable
and @Html.EditorForModel()
to render my View.
View
<form action="xx" method="POST">
<table id="myTable" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.Field1)
</th>
<th>
@Html.DisplayNameFor(model => model.Field2)
</th>
<th>
@Html.DisplayNameFor(model => model.Field3)
</th>
</tr>
</thead>
<tbody>
@if (Model != null)
{
@Html.EditorForModel()
}
</tbody>
<tfoot></tfoot>
</table>
<input type="submit" value="submit" />
</form>
Script
$("#myTable").dataTable({
searching: false,
ordering: false,
responsive: true,
"bLengthChange" : false,
"pageLength": 20,
"bStateSave": true
});
Controller
[HttpPost]
public ActionResult MyAction(List<MyModel> MyListModel)
This method works great if the data is no more than 1 page in dataTables
. if its more than 1 page, then My Controller either only can receive the List Data
of the first page or receive nothing(null)
How should I bind all of my data in DataTables
from View to Controller? This binding should include all pages, not only the first one
I'm unsure how you're triggering the update of data, so assuming it's a button the following should work:
$('#your-button').on('click', function(e){
var data = ('#myTable').DataTable().$('input,select,textarea').serialize();
$.ajax({
url: '/MyController/MyAction/',
data: data,
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
});
Edit 1:
As per this answer to How to post data for the whole table using jQuery DataTables, if you're set on using a form use the following:
var table = $('#myTable').DataTable();
$('#myForm').on('submit', function(e){
var form = this;
var params = table.$('input,select,textarea').serializeArray();
$.each(params, function(){
if(!$.contains(document, form[this.name])){
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
});
});