How can we access the datatable individual column searched value to controller(C# .net Mvc) while using the server side processing? - datatable

I have used datatable individual column searching .
below is my js code:
var BindDataTable = function (response) {
var oTable;
$("#example").DataTable({
initComplete: function () {
// Apply the search
this.api().columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change clear',
function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
},
"searching": true,
// dom: '<"class">Blfrtip',
dom: "<'row mb-3'<'col-sm-12 col-md-2 col-lg-2'l><'col-sm-12 col-md-10 col-lg-10 datatableButtonsCon text-right'Bf>>" +
"<'row'<'col-sm-12 datatablesData'tr>>" +
"<'row mt-4'<'col-sm-12 col-md-4 col-lg-6 infoCon'i><'col-sm-12 col-md-8 col-lg-6 pagCon'p>>",
"bServerSide": true,
"sAjaxSource": "/AspNetStudents/GetStudents",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
type: "POST",
data:aoData,
url: sSource,
success:fnCallback
})
},
"aoColumns": [
{ "mData": "Name" },
{ "mData": "RollNo" },
{ "mData": "CellNo" },
{ "mData": "JoiningDate" },
{ "mData": "ClassName" },
{ "mData": "TotalWithoutAdmission" },
{ "mData": "UserStatus" },
]
});
oTable = $('#example').DataTable();
oTable.columns(0).search("data");
oTable.draw();
I have also attached the backend C# code to access the individual datatable column value to controller.
How can we access the datatable individual column searched value to controller(C# .net Mvc) while using the server side processing?

just as an idea, I know it makes ajax request every time a draw method is called.In this case, the data can be serialized and sent,then the searched data can be accessed by performing a parse operation in the controller.
$.ajax({
type: "POST",
dataType: "json",
url: sSource,
data: function (data) {
data.filters = $(".filter").serialize();
},
success:fnCallback
})
// search
$(".filter").on("change", function (e) {
e.preventDefault();
table.draw();
});
...
// in controller
// parse request

Related

fetch data on dropdown change event from database to dataTables using ajax in Codeigniter 4

fetch data from database to datatables using ajax on dropdown change.
controller and model is working fine when use simple dropdown change event using ajax, but when try to fetch data to dataTables then show an error
no data available
Controller:
public function getStudents()
{
$model = new ModelAjax();
$sessionid = $this->request->getVar('sessionid');
$classid = $this->request->getVar('classid');
$data = $model->getStudents($sessionid,$classid);
echo json_encode($data);
}
Model:
public function getStudents($sessionid,$classid)
{
$model = new ModelStudent();
$array = ['sessionid' => $sessionid, 'classid' => $classid];
$data = $model->select('tblstudent.studentname,tblstudent.fathername, tblstudent.rollno ,tblstudent.mobile1')
->join('tblenrollment','tblstudent.id = tblenrollment.studentid','left')
->where($array)
->findAll();
return $data;
}
Script:
$("#classid").change(function(){
var sessionid = $("#sessionid").val();
var classid = $(this).val();
$('#example').DataTable({
ajax: {
url: "<?php echo site_url('Ajax/getStudents'); ?>",
type: "POST",
data: function(d){
d.sessionid = $("#sessionid").val();
d.classid = $("#classid").val();
}
},
dom: 'Bfrtip',
iDisplayLength: 15,
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'pageLength'
],
search: true
});
});
Finally succeeded to do it:
$("#classid").change(function(){
var sessionid = $("#sessionid").val();
var classid = $(this).val();
$.ajax({
url : "<?php echo site_url('Ajax/getStudents'); ?>",
method : "POST",
data : {sessionid: sessionid, classid: classid},
async : true,
dataType : 'json',
success: function(data)
{
$('#example').DataTable({
destroy: true,
data : data,
columns: [
{ data: 'studentname', title: "StudentName" },
{ data: 'fathername', title: "Father Name" },
{ data: 'rollno', title: "RollNo" },
{ data: 'mobile1', title: "Mobile" }
],
dom: 'Bfrtip',
iDisplayLength: 15,
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'pageLength'
],
search: true
});
}
});
return false;
});

Select2 - Change name="param" to other name for post request

I have the following search box for getting data from backend:
<select class="form-control kt-select2" id="megaagent_rainmaker_select" name="param" multiple="multiple" style="width: 100%"></select>
This is my select2 javascript code:
var rainmakerSelect = function () {
// Private functions
var demos = function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// multi select
$('#megaagent_rainmaker_select').select2({
language: "es",
placeholder: "Escriba y seleccione",
allowClear: true,
maximumSelectionLength: 1,
ajax: {
url: '/admin/megaagent/getrainmaker',
type: "get",
dataType: 'json',
delay: 150,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
return {
init: function () {
demos();
}
};
}();
jQuery(document).ready(function () {
rainmakerSelect.init();
});
I get results returned and I can select one without problem.
After I select a value, I send update request to backend, this is my payload:
{
"_token": "bPl0hZJQxw5wAxNCqVOOKqrXXwkD5AZZOFPumrpC",
"mc_id": "11",
"megaagent_id": "16",
"megaagent_name": "David Cortada",
"megaagent_business_name": "bsame cambio",
"megaagent_uma_id": "umaid",
"megaagent_api_key": "apikey",
"param": "963",
"megaagent_phone_number": "phone",
"megaagent_email": "email",
"megaagent_address": "address",
"megaagent_facebook": "fb",
"megaagent_instagram": "inst",
"megaagent_twitter": "twi",
"megaagent_linkedin": "link",
"megaagent_image": "image",
"megaagent_status": "Activo"
}
What I want to achieve is to change param name to other on post request (example: "megaagent_rainmaker_id" = "963",.
I changed it in <select name="param"> but that breaks the search, no results are returned when I type in search box.
Does anyone knows the solution for this?
Regards

Kendo UI Grid with form in popup

I want to implement individual form for ajax call. I want to have a command, which opens new popup window with one field, user fills this field and then clicks "Send" and then I do an ajax call to controller. My code:
$(document).ready(function () {
var grid = $("#memberList-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("MemberSearchList", "RandomPoolSelection"))",
type: "POST",
dataType: "json",
data: function () {
var data = {
SearchMember: $('##Html.IdFor(model => model.SearchMember)').val(),
SelectionId: $('#SelectionId').val()
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: #(Model.PageSize),
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [#(Model.AvailablePageSizes)],
#await Html.PartialAsync("_GridPagerMessages")
},
scrollable: false,
columns: [
{
field: "PrimaryID",
title: "#T("PoolMemberList.Fields.PrimaryID")",
width: 150
},
{
field: "FirstName",
title: "#T("PoolMemberList.Fields.FirstName")",
width: 150
},
{
command:
{
text: "Exclude",
click: showExclude
},
title: " ",
width: 100
}
]
});
wndExclude = $("#exclude")
.kendoWindow({
title: "Excuse Reason",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
excludeTemplate = kendo.template($("#excludeTemplate").html());
});
function showExclude(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wndExclude.content(excludeTemplate(dataItem));
wndExclude.center().open();
}
and template :
<script type="text/x-kendo-template" id="excludeTemplate">
<div id="exclude-container">
<input type="text" class="k-input k-textbox" id="note">
<br />
</div>
</script>
how to implement sending this data (with ID) to controller?
A simple way to do what you want is using a partial view.
this is your command grid
{
command:
{
text: "Exclude",
click: showExclude
},
title: " ",
width: 100
}
and here your function :
function showExclude(e) {
$(document.body).append('<div id="excludeWindow" class="k-rtl"></div>');
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$('#excludeWindow').kendoWindow({
width: "80%",
title: 'excludeForm',
modal: true,
resizable: false,
content: "/YourController/GetPartial?id=" + dataItem.Id,
actions: [
"Close"
],
refresh: function () {
$("#excludeWindow").data('kendoWindow').center();
},
close: function() {
setTimeout(function () {
$('#excludeWindow').kendoWindow('destroy');
}, 200);
}
}).data('kendoWindow');
}
After clicking on the button, you load your window(popup) and call an action that loads a partial view to fill the content of the window.
You can pass whatever you want to your partial view (for example, here I just send Id)
public ActionResult GetPartial(Guid id)
{
var viewModel= new ViewModelExclude
{
Id = id,
};
return PartialView("_exclude", viewModel);
}
and the partial view is something like this:
#model ViewModelExclude
#using (Html.BeginForm("", "Your action", FormMethod.Post, new { id = "SendForm"}))
{
<input class="k-rtl" name="#nameof(Model.Id)" value="#Model.Id">
<button type="submit" class="btn btn-primary">Send</button>
}
and then call Your ajax after clicking on send button:
$("#SendForm").submit(function (e) {
e.preventDefault();
var form = $(this);
var formData = new FormData(this);
$.ajax({
type: "POST",
url: '#Url.Action("send", "yourController"),
data: formData,
contentType: false,
processData: false,
success: function (data) {
},
error: function (data) {
}
});
});
Your send action something like this:
[HttpPost]
public ActionResult Send(ViewModelExclude view)
{
....
return Json();
}

Datatables: Button for Showing Photo for Each Filename

I am very new to Datatables and this might be simple, but surely I am missing something. I am trying to create a button column that uses the filename of each row and uses it to make an ajax call to display a picture on click. What I get wrong is that, every button of the column displays the same image, and not the image of the filename for each row. Here is the code:
$.ajax ({
url: "http:// ...... /Services/DBPrintDatatable?customer_id=" + projectid,
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"aaSorting": [],
"columns": [
{ "data": "upload_date" },
{ "data": "filename" },
{ "data": "uploader" },
{ "data": "upload_place" },
{ "data": "is_ok" },
{ "data": "custom_verdict" },
{
data: { "data": "filename" },
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename='+ { 'data': 'filename' }>Show</a>";
}
},
] ,
});
Thank you in advance!
If the image url required is like
http://......./Services/DBShowImage?filename=filenameFromData
Then you should generate it first inside the render like below code
href='http://......./Services/DBShowImage?filename="+ row.filename+"';
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename="+ row.filename+"'>Show</a>";
}

Is it possible for pagination last button reload in jquery datatable?

Is it possible for pagination last button reload in jquery datatable?
I have used jquery datable ,Now my record more than one lack's data.
So I have page initialize 1000 record load and then last pagination button click reload data 1000.
can give me any other idea...?
For your reference:
$("#tblExmaple").hide();
jQuery(document).ready(function ($) {
getRecords();
function getRecords() {
jQuery.support.cors = true;
$.ajax({
cache: false,
type: "GET",
url: "http://localhost:1111/TestSample/api/getRecords",
datatype: "json",
data: { Arg1: "Values1",Arg2: "Values2",Arg2: "Values3" },
statusCode: {
200: function (data) {
$.each(data, function (index, obj) {
var colRes1 = obj.Res1;
var colRes2 = obj.Res2;
var dataAdd = [colRes1, colRes2];
getData.push(dataAdd);
});
// Server Side Code
setTimeout(function () {
$('#tblExmaple').dataTable({
"sPaginationType": "full_numbers",
"sScrollXInner": "50%",
"sScrollyInner": "110%",
"aaData": getData,
"iDisplayLength": 8,
"sInfoEmpty": false,
"bLengthChange": false,
"aoColumns": [
{ "sTitle": "Column1" },
{ "sTitle": "Column2" }
];
})
}, 500);
setTimeout(function () {
$("#tblExmaple").show();
}, 500);
},
408: function (data) {
var response_Text = JSON.stringify(data, undefined, 50);
if (data.response_Text == undefined) {
window.location = "/Home/Index";
}
else {
timeoutClear();
}
}
}
});
}

Resources