how to convert /Date(-664768800000)/ to datetime in c# - javascript

I get item from database like this :
{8.12.1948 00:00:00}
and when i send it to datatable in view it seems like this:
/Date(-664768800000)/
how can i handle this ?
public ActionResult GetList()
{
context entity = new context();
var list = entity.People.Select(x =>
new
{
EmployeeID = x.EmployeeID,
BirthDate =x.BirthDate,
}).ToList();
return Json(new { data = list }, JsonRequestBehavior.AllowGet);
}
$(document).ready(function () {
$('#example').DataTable({
"bDestroy": true,
"ajax": {
"url": '/Home/GetList',
"type": "GET",
"datatype": "json",
async: false,
cache: false,
"dataSrc": function (json) {
return json.data;
}
},
columns:
[
{ data: "EmployeeID"},
{ data: "BirthDate" },
]
})
});

Related

How can I pass my console log result to my ajax so that i can insert it in DB?

I am making a matchmaking system. My question is, how can I insert my console.log result into my database? The result from console.log happens when there's the same level in my DB.
, For example, testing 4 has level 1 and testing 1 has level 1. They'll
be joined in 1 array because they have the same level
Same for the others also. I have provided my codes and screenshot of my target below. Any help will be appreciated. Thank you very much.
ajax fetch:
<script>
let ajaxResult = []; // the pushed data will be saved here
let table;
let base_url = "<?php echo base_url();?>";
let result = [];
const combine = (source) => {
return source[0].data.reduce((acc, curr) => {
const [entryID, entryName, level] = curr;
if (acc[level])
acc[level].push({
entryID,
entryName,
level
});
else
acc[level] = [{
entryID,
entryName,
level
}];
return acc;
}, {})
}
$(document).ready(function() {
//datatables
table = $("#entry_list1").DataTable({
processing: false,
serverSide: true,
order: [],
searching: false,
paging: false,
info: false,
ajax: {
url: "<?php echo site_url('controller/fetch_players')?>",
type: "POST",
async: true,
dataType: "json",
success: function(data) {
ajaxResult.push(data); // I'm pushing my data to my ajaxResult variable
result = combine(ajaxResult); // Cleanup your data here.
console.log(combine(ajaxResult)); // The result in image i provided above is from here.
},
},
"columnDefs": [{
"targets": [0], //first column
"orderable": false, //set not orderable
},
{
"targets": [-1], //last column
"orderable": false, //set not orderable
},
],
});
});
</script>
ajax insert:
// i want to pass my ajaxResult = []; here so that i can insert it into my database
<script type="text/javascript">
$("#insertMe").submit(function(event) {
var form = $('#insertMe')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "<?php echo base_url('controller/insertFunction'); ?>",
cache: false,
contentType: false,
processData: false,
data: formData,
type: "post",
async: false,
dataType: 'json',
success: function(data){
},
});
});
</script>
controller:
function inserFunction() {
$this->db->insert('matching', $data);
}

ajax datatable, cannot retrieve data

I Edited my code, but the problem now is i can't retrieve my data but there is no error in my code, Also i have records in my database. I can't figure it out why my data is not dislaying.
//Controller - where i getting my data in database.
public ActionResult GetEmployeeFlexiSched()
{
string query = "exec spdGetEmployeeFlexiSched";
string strReturn = GlobalFunction.DataTableToJSON(GlobalFunction.TableFromMSSQL(conn, query));
return Json(new { success = true, data = strReturn }, JsonRequestBehavior.AllowGet);
}
<script>
$(document).ready(function () {
var dataTable = $('#OedTB').DataTable({
"language": {
emptyTable: "No Transaction"
},
ajax: {
url: '#Url.Action("GetEmployeeFlexiSched", "FlexiSchedule")',
dataType: "json",
retrieve: "true",
processing: "true",
serverSide: "true",
type: "POST",
dataSrc: "",
},
order: [],
columnDefs: [
{
orderable: false,
}
],
columns: [
{data: "TranNo"},
{data: "FullName"},
{
data: "TranNo",
render: function (data, type, row, meta) {
return '<button type="button" class="btn btm-sm btn-outline-danger viewdetails" id="' + data + '"><i class="fas fa-info-circle"></i></button>';
}
},
]
});
});
</script>

Using JSON data to filll "columns" in datatable

I am getting JSON data via AJAX and my data are in a result object. The fields of which can be accessed as in success: function(result)
result.map.count[0].name
result.map.count[0].count
I would like to show name and count as two columns of my datatable.
My ajax request is written as
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
I am able to get data as "result" here
result.map.count[0].name
result.map.count[0].count
}
});
},
columns: []
})
what should I put in columns[] to show these fields?
columns: []
In your datatable configuration,add the following
data: [[result.map.count.name,result.map.count.count]], // make it as array of values
columns: [
{
"sClass": "center",
"name": "Name"
},
{
"sClass": "center",
"name": "Count"
},
]
Please check here for more details
https://datatables.net/examples/data_sources/js_array.html
I've found my answer.
I need to write a callback function that returns the data (array) which is found from my object.
Code:
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
var dataToUse = {};
dataToUse.data = result.map.count;
callback(dataToUse);
}
});
},
columns: [
"data": "name",
"data": "count"
]
})
}
Please try this.
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
callback(result.map.count);
}
});
},
// Columns
columns: [{
title: "Name",
name: "name",
}, {
title: "Count",
name: "count"
}]
});

Fill WebGrid with dataset

I have problems returning my DataSet to my WebGrid, previously I was filling it with a connection to my Entity and I had no problems, the fact is that for security reasons in my work I can not use more than a connection already "Default"
before:
using (SiniestrosEntities dc = new SiniestrosEntities())
{
var Condicion = dc.CAT_Doctos_Proveedores.OrderBy(a =>
a.id_Proveedor).ToList();
return Json(new
{
data = Condicion
}, JsonRequestBehavior.AllowGet);
}
Returning my data to my View, I had no problem.
Now I have my database query in a DATSET and I want to return it with a Json to my view ... but I get the following error:
DataTables warning: table id=myDatatable - Requested unknown parameter 'nFacturaProveedoresID' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
My Code JS
var oTable = $('#myDatatable').DataTable({
"ajax": {
"url": '/Facturas/GetEmployees',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "nFacturaProveedoresID", "autoWidth": true },
{ "data": "nSiniestroid", "autoWidth": true },
{ "data": "cSerie", "autoWidth": true },
{ "data": "cFolio", "autoWidth": true },
{ "data": "dtFechaFactura", "autoWidth": true },
{ "data": "cConcepto", "autoWidth": true },
{ "data": "mTotal", "autoWidth": true },
{ "data": "dtFechaRegistro", "autoWidth": true },
{ "data": "nFacturaProveedoresID", "width": "20px", "render": function (data) {
return '<a class="popup" href="/Facturas/Save/' + data + '">Editar</a>';
}
},
{
"data": "EmployeeID", "width": "50px", "render": function (data)
{
return '<a class="popup" href="/Facturas/Delete' + data + '">Borrar</a>';
}
}
]
})
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
})
function OpenPopup(pageUrl) {
debugger;
var $pageContent = $('<div/>');
$pageContent.load(pageUrl, function () {
$('#popupForm', $pageContent).removeData('validator');
$('#popupForm', $pageContent).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
draggable: true,
autoOpen: false,
resizable: true,
model: true,
title: 'ActualizaciĆ³n de Datos',
height: 850,
width: 1650,
close: function () {
$dialog.dialog('destroy').remove();
}
})
debugger;
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type: "POST",
url: url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
$dialog.dialog('close');
oTable.ajax.reload();
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
})
My Controller
public ActionResult GetEmployees()
{
try
{
int proveedor = Convert.ToInt32(Session["IdProveedor"]);
DataSet ConsultaGrid = new DataSet();
ConsultasProveedores ConsultaFacturas = new ConsultasProveedores();
ConsultaGrid = ConsultaFacturas.ConsultaGen(Convert.ToString(proveedor));
List<string> list = new List<string>();
list.Add(ConsultaGrid.Tables[0].Rows[0]["nFacturaProveedoresID"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["nSiniestroid"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["cSerie"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["cFolio"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["dtFechaFactura"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["cConcepto"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["mTotal"].ToString());
list.Add(ConsultaGrid.Tables[0].Rows[0]["dtFechaRegistro"].ToString());
return Json(new
{
data = list
}, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return View("Login");
}
}
You are returning a list of strings (one item per colum). Datatable will expect an array of objects with each object has the defined columns:
"columns": [
{ "data": "nFacturaProveedoresID", "autoWidth": true },
{ "data": "nSiniestroid", "autoWidth": true },
and so on
Your controller should return something like List<Proveedor> where proveedor is:
public class Proveedor {
public int nFacturaProveedoresID {get; set; }
public int nSiniestroid {get; set;}
etc
}
your controller should be like:
public ActionResult GetEmployees()
{
try
{
int proveedor = Convert.ToInt32(Session["IdProveedor"]);
DataSet ConsultaGrid = new DataSet();
ConsultasProveedores ConsultaFacturas = new ConsultasProveedores();
ConsultaGrid = ConsultaFacturas.ConsultaGen(Convert.ToString(proveedor));
List<Proveedor> list = new List<Proveedor>();
list.Add(new Proveedor {
nFacturaProveedoresID = (int)ConsultaGrid.Tables[0].Rows[0]["nFacturaProveedoresID"],
nSiniestroid = (int)ConsultaGrid.Tables[0].Rows[0]["nSiniestroid"],
//rest of fields
});
return Json(new
{
data = list
}, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return View("Login");
}
}

implement server side pagination on datatable

inside mvc controller I'm receiving MyTable as parameter
public JsonResult GetListOfData(JobTable result)
{
var query = ... get data ..
IQueryable<MyData> resData;
resData.recordsFiltered = query.Skip(result.start).Take(50).AsQueryable();
resData.recordsTotal = query.Count();
...
return Json(resData, JsonRequestBehavior.AllowGet);
}
Inside view I have js code which initialize jquery data table
function drawTable() {
var table = $('#myTable').dataTable({
processing: true,
serverSide: true,
searching: false,
lengthChange: false,
displayLength: 25,
order: [[5, 'desc']],
ajax: {
url: '#Url.Action("GetListOfData", "Index")',
data: function (d) {
...
d.status = $('#Status').val(),
d.dateFrom = $('#DateFrom').val(),
d.dateTo = $('#DateTo').val(),
...
}
},
columns: [
{ data: 'Id' },
{ data: 'Status' },
{ data: 'CreatedDate' },
...
],
columnDefs: [
{
targets: [0, 3, 4],
orderable: false
},
{
render: function (data, type, row) {
return '<i class="glyphicon glyphicon-folder-open"></i>'
},
title: '',
targets: 0
}
]
});
}
Question is:
What I'm missing here to successfully implement server side pagination, what should I do to recognize clicked number inside view and receive that as part of MyTable parameter?
i just fixed it!!
recordFiltered and recordsTotal should be of same length.
i was doing at serverside :
return Json(new
{
draw = param.draw,
recordsTotal = allData.Count(),
recordsFiltered = filteredData.Count(),
data = result
}, JsonRequestBehavior.AllowGet);
now i did:
return Json(new
{
draw = param.draw,
recordsTotal = allData.Count(),
recordsFiltered = allData.Count(),
data = result
}, JsonRequestBehavior.AllowGet);

Categories

Resources