how to implement (Server-side) SearchPanes of DataTables in mvc core - datatables

I need an example of a (Server-side Procssing) SearchPanes implementation of DataTables in mvc core
In the link I have an example of implementing datatables including operations such as Sorting, pagination and search but about the implementation of searchPanes please help me

You could use Juery Ajax to call the MVC action method and load data, then, setting the JQuery DataTable's "searchPanes", "columnDefs" and "dom: 'Pfrtip'," property to implement the SearchPanes function. Sample Code as below:
Code in the Action method:
[HttpPost]
public JsonResult GetData()
{
List<Employee> employees = new List<Employee>()
{
new Employee(){ DT_RowId="row_1", First_Name="Tiger", Last_Name="Nixon", Position="System Architect", Email="t.nixon#datatables.net", Office="Edinburgh", Extn="5421", Age="61", Salary="320800", Start_date="2011-04-25"},
new Employee(){ DT_RowId="row_2", First_Name="Garrett", Last_Name="Winters", Position="Office Manager", Email="t.nixon#datatables.net", Office="London", Extn="7580", Age="61", Salary="13800", Start_date="2011-04-25"},
new Employee(){ DT_RowId="row_3", First_Name="Timothy", Last_Name="Mooney", Position="System Architect", Email="t.nixon#datatables.net", Office="San Francisco", Extn="5384", Age="61", Salary="85675", Start_date="2011-04-25"},
new Employee(){ DT_RowId="row_4", First_Name="Unity", Last_Name="Butler", Position="Marketing Designer", Email="t.nixon#datatables.net", Office="San Francisco", Extn="9421", Age="61", Salary="452500", Start_date="2011-04-25"},
new Employee(){ DT_RowId="row_5", First_Name="Vivian", Last_Name="Harrell", Position="Financial Controller", Email="t.nixon#datatables.net", Office="London", Extn="7439", Age="61", Salary="67500", Start_date="2011-04-25"},
};
return Json(employees);
}
Code in the View Page:
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/searchpanes/1.1.1/css/searchPanes.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/select/1.3.1/css/select.dataTables.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/searchpanes/1.1.1/js/dataTables.searchPanes.min.js"></script>
<script src="https://cdn.datatables.net/select/1.3.1/js/dataTables.select.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
JQuery script:
<script>
$(document).ready(function () {
$(function () {
$.ajax({
type: "POST",
url: "/Home/GetData",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function OnSuccess(response) {
$("#example").DataTable(
{
bLengthChange: true,
bFilter: true,
bSort: true,
bPaginate: true,
data: response,
searchPanes: {
columns: [2, 5],
layout: 'columns-2',
},
columnDefs: [{
searchPanes: {
show: true
},
targets: [5]
}],
dom: 'Pfrtip',
columns: [{
'data': null, render: function (data, type, row) {
// Combine the first and last names into a single table field
return data.first_Name + ' ' + data.last_Name;
}
},
{ 'data': 'position' },
{ 'data': 'office' },
{ 'data': 'extn' },
{ 'data': 'start_date' },
{
'data': 'salary',
render: $.fn.dataTable.render.number(',', '.', 0, '$')
}
]
});
};
});
</script>
The output as below:
More detail information, please check the following links:
Populate jQuery DataTables in Asp.net MVC
JQuery DataTables SearchPanes
DataTables SearchPanes Examples

Your server's response JSON should have an object named searchPane; the
content of this object is something like this:
$searchPanes['options'][$key][]=["label" => $v['label'], "total" => $v['total'], "value" => $v['value'], "count" => 0];

Related

Asp.net core Razor Page - JQ data table not load data

I have an Asp.net core project with Razor Page ,I try to implement a JQ data table but the data not load.
Here is the Javascript code:
$('#dataList').DataTable({
// "iDisplayLength": 100,
// "sPaginationType": "full_numbers",
processing: true,
serverSide: true,
ajax: {
async: true,
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/CoursesDP/?handler=Data',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: function (d) {
// note: d is created by datatable, the structure of d is the same with DataTableParameters model above
// console.log(JSON.stringify(d));
return JSON.stringify(d);
},
success: function (r) {
console.log(r);
}
},
})
I write the data is coming to console:
{"draw":1,"recordsTotal":11,"recordsFiltered":11,"data":[["oooo"],["ccc"],["aaa"],["pppp"],["pppp"],["yyy"],["12"],["pppp"],["pppp"],["pppp"],["fff"]]}
This is the html code:
<table id="dataList" class="display" style="width:100%">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseDP[0].CourseName)
</th>
</tr>
</thead>
but the data not load to the data table .
What can I do?
The following is a working sample using DataTables with testing data, you can refer to it.
CoursesDP.cshtml:
#page
#model ModelValidation_MVC_.Pages.CourseDB.CoursesDPModel
#{
ViewData["Title"] = "CoursesDP";
}
<h1>CourseDP</h1>
<div>
<table id="dataList" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>id</th>
<th>name</th>
<th>age</th>
<th>phone</th>
<th>email</th>
</tr>
</thead>
</table>
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$('#dataList').DataTable({
"processing": true,
"serverSide": true,
ajax: {
type: "POST",
url: '/CourseDB/CoursesDP/?handler=Data',
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'age' },
{ data: 'phone' },
{ data: 'email' }
]
})
</script>
}
CoursesDP.cshtml.cs:
[IgnoreAntiforgeryToken]
public class CoursesDPModel : PageModel
{
public static List<TestDT> testDTs = new List<TestDT> { new TestDT {id=1, name = "TestDT1", age = 1, phone = "1", email = "TestDT1#.com" },
new TestDT {id=2, name = "TestDT2", age = 2, phone = "2", email = "TestDT2#.com" }, new TestDT {id=3, name = "TestDT3", age = 3, phone = "3", email = "TestDT3#.com" } ,
new TestDT {id=4, name = "TestDT4", age = 4, phone = "4", email = "TestDT4#.com" }, new TestDT {id=5, name = "TestDT5", age = 5, phone = "5", email = "TestDT5#.com" } ,
new TestDT {id=6, name = "TestDT6", age = 6, phone = "6", email = "TestDT6#.com" },new TestDT {id=7, name = "TestDT7", age = 7, phone = "7", email = "TestDT7#.com" },};
public static List<TestId> testIds = new List<TestId> { new TestId { id = 1 }, new TestId { id = 2 } };
public IActionResult OnGet()
{
return Page();
}
public JsonResult OnPostData()
{
Postdata postdata = new Postdata { draw = 1, recordsTotal =7, recordsFiltered = 7, data = testDTs };
return new JsonResult(postdata);
}
}
result:

jquery datatable does not get initialized with given response

I want to initialize data table with my generated response
my response looks like this
{data: Array(3), status: true}
data : Array(3)
0 : {countryId: 1, countryName: "sampleCountry", countryShortCode: "sampleCode", status: "yes"}
1 : {countryId: 2, countryName: "pakistan", countryShortCode: "pak", status: "yes"}
2 : {countryId: 3, countryName: "sample2", countryShortCode: "pak", status: "yes"}
please look at my html
<table class="table table-striped" id="countryTable">
<thead>
<tr>
<th>S.NO.</th>
<th>Country Name</th>
<th>Country Short Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
please look at my datatable initialization
$.ajax({
url : url,
type:"get",
contentType:'application/json; charset=utf-8',
dataType: 'json' ,
async: false,
success:function(response)
{
alert(response.data);
$('#countryTable').DataTable( {
"fnRowCallback" : function(nRow, aData, iDisplayIndex){
$("td:first", nRow).html(iDisplayIndex +1);
return nRow;
},
destroy: true,
mydata: response.data,
columns: [
{ mydata:'countryId'},
{ mydata:'countryName'},
{ mydata:'countryShortCode'}
]
} );
console.log(response);
}
});
after initialization data table shows as No data available in table but table gets initialized with datatable plugin .
data is not coming into table.
what went wrong in my code please help me.
The code looks fine, you just need to change mydata to data, like this:
var response = {
data: [{
countryId: 1,
countryName: "sampleCountry",
countryShortCode: "sampleCode",
status: "yes"
},
{
countryId: 2,
countryName: "pakistan",
countryShortCode: "pak",
status: "yes"
},
{
countryId: 3,
countryName: "sample2",
countryShortCode: "pak",
status: "yes"
}
],
status: true
}
$('#countryTable').DataTable({
"fnRowCallback": function(nRow, aData, iDisplayIndex) {
$("td:first", nRow).html(iDisplayIndex + 1);
return nRow;
},
destroy: true,
data: response.data,
columns: [{
data: 'countryId'
},
{
data: 'countryName'
},
{
data: 'countryShortCode'
}
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table class="table table-striped" id="countryTable">
<thead>
<tr>
<th>S.NO.</th>
<th>Country Name</th>
<th>Country Short Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Vue instance in double quotes

I use vue instance but it is not parsing , i think problem is relevant with using double quotes in Metro.dialog.Create.content.
Here is the main page include table and it works correctly.I added when dblclick table on main page open dialog and another table showing in this dialog.
var app2= new Vue({
el: '#appTable',
data: {
squads: [
]
},
mounted: function () {
Metro.init();
var self = this;
$.ajax({
url: '#Url.Action("Find", "Squad")',
method: 'GET',
success: function (data) {
self.squads = data;
},
});
},
methods:{
clickList: function (squad) {
bindSquadToEditTable(squad.ID);
Metro.dialog.create({
title: "Team",
content:
'<div class ="row-4-3 rowspan" >'+
'<div id="appTableMembers">'+
'<table class="table cell-border ">'+
'<thead>'+
'<tr>'+
'<th>Personal Code</th>'+
'<th>Name</th>'+
'<th>Email</th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
"<tr v-for=squad in members :key=squad.PersonalCode > <td>{{squad.PersonalCode}}</td> <td>{{squad.FullName}}</td> <td>{{squad.Email}}</td>"+
'</tr>'+
'</tbody>'+
'</table>'+
'</div>',
});
}
}
});
That is my Main page;
<div id="appTable">
<table class="table striped">
<thead>
<tr>
<th>Code</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr v-for="squad in squads" :key="squad.Code" v-on:dblclick="clickList(squad)">
<td>{{squad.Code}}</td> <td>{{squad.Description}}</td>
</tr>
</tbody>
</table>
</div>
Here is the binding data to dialog ;
<script>
function bindSquadToEditTable(ID){
app3 = new Vue({
el: 'appTableMembers',
data: {
members:[]
},
mounted:function(){
Metro.init();
var self = this;
$.ajax({
type: "GET",
"url": '#Url.Action("FindByID", "Squad")',
"data": { id: ID },
"dataSrc": "",
success: function(data){
self.members = data;
},
});
}
})
}
</script>
I was curious how this would work so I threw together a quick test. Worked fine using the hidden <div> for the modal content.
HTML
<html>
<head>
<link rel="stylesheet" href="https://cdn.metroui.org.ua/v4/css/metro-all.min.css">
</head>
<body>
<div id="app">
<input type="button" value="modal" #click="showModal" />
<div style="display: none" ref="modalContent">
<div>My name is {{name}}</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.metroui.org.ua/v4/js/metro.min.js"></script>
</body>
</html>
Javascript
new Vue({
el: "#app",
data: {
name: 'Sample User'
},
methods: {
showModal: function() {
Metro.dialog.create({
title: "Modal Title",
content: this.getModalContent
});
},
getModalContent: function() {
return this.$refs.modalContent.innerHTML;
}
}
});
I change the my opinion and i will implement modal in the script;
<script type="text/template" id="data-input-form-template" >
<label>Code</label>
<input type="text" v-model="squad[0].Code"/>
<label>Name</label>
<input type="text" v-model="squad[0].Name" />
<label>Description</label>
<textarea style="height:175px" v-model="squad[0].Description"></textarea>
<div id="appTableMembers">
<table class="cell-border" >
<thead>
<tr>
<th>Personal Code</th>
<th>Adı</th>
</tr>
</thead>
<tbody>
<tr v-for="m in squad[0].members">
<td>{{m.PersonalCode}}</td>
<td>{{m.FullName}}</td>
</tr>
</tbody>
</table>
</div>
</script>
And this my openDialog function;
function openDialog(ID) {
var html = $('#data-input-form-template').html();
$('#data-input-form').html(html);
app4 = new Vue({
el:'#data-input-form',
data: function(){
return {
squad: [{
members: []
}]
}
},
mounted:function(){
Metro.init();
var self = this;
$.ajax({
type: "GET",
"url": '#Url.Action("FindByID", "Squad")',
"data": { id: ID },
"dataSrc": "",
success: function (data) {
self.squad = data;
},
error: function (error) {
alert(error);
}
});
}
});
Metro.dialog.open('#demoDialog1');
}
Main Page html;
<div class="dialog" data-role="dialog" id="demoDialog1"> src="#" />
<div class="dialog-content" style="height:400px">
<form id="data-input-form">
</form>
</div>
</div>

How to reload dataTables from VueJS after adding or editing?

I'd like to know how I can use this same approach when loading data from database through an api. In the first time the dataTables loads fine. However, when I add a new record, then I need to load my dataTables again with the new record. Here's my html code:
<table class="table table-striped table-bordered table-hover" id="dataTables-eventos">
<thead>
<tr class="tbheader">
<th class="text-center">#</th>
<th>Nome do Evento</th>
<th class="text-center">Editar</th>
<th class="text-center">Deletar</th>
</tr>
</thead>
<tbody>
<tr v-for="ev in eventos" :key="ev.id" track-by="id">
<td class="text-center">{{ ev.id }}</td>
<td>{{ ev.name }}</td>
<td class="text-center"><a class="cursorpointer" v-on:click="showMessage()"><span class="glyphicon glyphicon-edit"></span></a></td>
<td class="text-center"><span class="glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
</table>
And here's my VueJS code:
mounted() {
this.getEventos();
},
methods: {
getEventos() {
axios.get('/api/eventos')
.then((response) => {
this.eventos = response.data})
.then((response) => {
$('#dataTables-eventos').DataTable({
responsive: true,
"aaSorting": [[ 1, "asc" ]],
"aoColumnDefs": [
{ "bSortable" : false, "aTargets": [0,2,3] },
{ "searchable": false, "aTargets": [2,3] }
],
language: {
url: '/js/dataTables/localization/pt_BR.json'
}
});
});
},
addNewRecord() {
axios.post('/api/eventos', { nomeEvento: this.nomeEvento });
}
So after adding (or editing) a new record on my DB how can I reload my dataTables so I can see the changes?
I just ran into a situation where I needed to use vue.js with datatables.net and had to use customized table html. I created a component that allowed me to format the table as I needed using template/v-for and refresh the datatable while preserving datatables.net functionality. I hope this helps someone down the road...
export default {
data() {
return {
dataTable: null
}
},
props: {
data: Array
},
watch: {
data() {
if (this.dataTable) {
this.dataTable.destroy();
}
this.$nextTick(() => {
this.dataTable = $("#table").DataTable({
language: {
emptyTable: "No Results Found"
}
});
});
}
}
}
You can do it without reloading all the data.
Just add this.nomeEvento to array eventos after posting to server.

Passing multiple row data from JQuery Datatables into ASP.NET 5 / MVC 6 view using a submit all button

I have an ASP.NET 5 MVC application. I am using JQuery Datatables downloaded from Datatables.net for rendering my grid.
I want to be able to select multiple records on the grid and through the click of one button to be able to update the status feild on all my records. I can't figure out how to pass the information from javascript to my MVC controller through the view. Here is what I have so far.
View Code
<table class="display " id="ExpenseTable">
<thead>
<tr>
<th></th>
<th>
#Html.DisplayNameFor(model => model.ApplicationUserid)
</th>
<th>
#Html.DisplayNameFor(model => model.ExpenseDate)
</th>
... </tr>
</thead>
<tbody>
#foreach (var item in (IEnumerable<Expense>)ViewData["Expenses"])
{
<tr>
<td></td>
<td>
#Html.DisplayFor(modelItem => item.User.FullName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ExpenseDate)
</td>
....
</tr>
}
</tbody>
</table>
#section Scripts {
<script>
//script is not complete
$(document).ready(function() {
var table = $('#ExpenseTable').DataTable({
dom: 'Bfrtip',
buttons: [
{
text: 'Approve All Selected Expenses',
action: function () {
}
}
],
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'multiple',
selector: 'td:first-child'
},
order: [[1, 'asc']],
} );
} );
I want to do something like this in the Controller
public IActionResult ApproveMany(IEnumerable<Expense> model)
{
foreach (var item in model)
{
item.Status = "Approved";
_context.Update(item);
_context.SaveChanges();
}
return RedirectToAction("StaffExpense"); ;
}
What I need help with is how I can take the button I have and when it is pushed take a collection of all the expense items that the user has selected on the grid, and then pass that collection into my controller so the edited changes can be pushed back to the database.
$('#updateButton').click(function ()
{
console.log("Selected rows: "+ table.rows('.selected').data().length);
var data = $.map(table.rows('.selected').data(), function (item)
{
console.log(item)
return item;
});
//Call your MVC Controller/API to do the update (pass data)
addData(data);
});
function addData(data)
{
//Add your controller name to url
/*POST*/
$.ajax({
url: '/Controller/ApproveMany',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
cache: false,
success: function (result)
{
alert(result);
},
error: function (xhr)
{
alert('error');
}
})
}
This link would be helpful for you to get the desired solution
http://www.gyrocode.com/articles/jquery-datatables-checkboxes/