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");
}
}
Related
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" },
]
})
});
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>
The error message is as below:
Requested unknown parameter 'emPONumber' for row 0, column 0
But emPONumber is in the JSON, why datatables still prompt this error?
<script type="text/javascript">
$(document).ready(function () {
var tableId = 'tablePurchaseOrders';
var table = $('#' + tableId).DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/GetAllUploadedPurchaseOrders',
type: 'GET',
data: function (data) {
//debugger;
var model = {
draw: data.draw,
start: data.start,
length: data.length,
columns: data.columns,
search: data.search,
order: data.order
};
return model;
},
failure: function (result) {
debugger;
alert("Error occurred while trying to get data from server: " + result.sEcho);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Error occurred while trying to get data from server!");
},
dataSrc: function (json) {
var _data = JSON.stringify(json.Data);
debugger;
return _data;
}
}
,
"columns": [
{ "data": "emPONumber", title: "emPONumber" },
{ "data": "ASMPONumber", title: "ASMPONumber" },
{ "data": "material", title: "material" }
]
});
});
</script>
json in dataSrc: function (json):
{"ContentEncoding":null,"ContentType":null,"Data":{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"emPONumber":"EM1234567","ASMPONumber":"A741000013","material":"26-00010","quantity":5,"UOM":"EA","asmPOQuantity":5,"createBy":"m","ASMPOYear":2018,"ASMPOMonth":6,"ASMPOVendor":"10008"}]},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}
json (_data) return by ajax in dataSrc:
{
"draw":1,
"recordsTotal":1,
"recordsFiltered":1,
"data":
[{
"emPONumber":"EM1234567",
"ASMPONumber":"A741000013",
"material":"26-00010",
"quantity":5,
"UOM":"EA",
"asmPOQuantity":5,
"createBy":"m",
"ASMPOYear":2018,
"ASMPOMonth":6,
"ASMPOVendor":"10008"
}]
}
Try
dataSrc: function (json) {
for(key in json.Data){ json[key] = json.Data[key]; }
delete json['Data'];
return json.data;
}
Here I have two JS files in which one is main JS file for parent page which contains Datatable which gets populated through ajax call. And other one is specifically for update functionality in which function is defined to update required values into database. That update is done in dialog box. So after successful update sweet alert comes which shows product is successfully updated. So what I want is updated values should be immediately reflected in Datatable of Parent Page. Currently it is showing old value only untill I refresh my page manually. Below are both JS files. And I am new in Javascript and Jquery. So Please help
var oTable;
var url_data_source;
(function(window, undefined) {
window.lastQuery = null;
function initDataSource(after_id) {
url_data_source = '/event/productlocation/ajax?action=data_source';
oTable = $('#datatable').dataTable({
"sAjaxSource": url_data_source,
"bProcessing": true,
"bServerSide": true,
"bFilter": false,
"bRetrieve": true,
"bScrollCollapse": true,
"iCookieDuration": 60*60*24,
"sCookiePrefix": "tkpd_datatable_",
"sPaginationType": "simple",
"scrollX": true,
"aaSorting": [ [0,'desc'] ],
"iDisplayLength": 20,
"aLengthMenu": [[20, 40, 60, 80, 100], [20, 40, 60, 80, 100]],
"oLanguage": {
"sInfoFiltered": "",
"sProcessing": " "
},
"aoColumns": [
{ "sName": "id", "mDataProp": "id"},
{ "sName": "location_id", "mDataProp": "location_id"},
{ "sName": "product_id", "mDataProp": "product_id"},
{ "sName": "status_str", "mDataProp": "status_str"},
{ "sName": "actions", "mDataProp": "actions"},
],
"fnDrawCallback":function(){
},
"initComplete": function(settings, json) {
$("#datatable_paginate").on("click", "#datatable_next", function(){
var after_id = ""
url_data_source = '/event/productlocation/ajax?action=data_source';
after_id_url = $("#after_id_url").val();
after_id = after_id_url.split("after_id=")
url_data_source += "&after_id="+after_id[1];
redraw();
});
},
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( {"name": "email", "value": $('#search_email').val()} );
if (after_id != "") {
aoData.push( {"name": "after_id", "value": after_id} );
}
if ($('#search_id_product').val()) {
aoData.push( {"name": "product_id", "value": $('#search_id_product').val()} );
}
$.ajax({
"dataType": 'json',
"type": "GET",
"url": url_data_source,
"data": aoData,
"success": function(result) {
var message_error = result.message_error
if (message_error) {
$('#datatable_processing').css("visibility","hidden");
swal({ title: message_error, type: "error"});
} else if (result.status == "OK") {
result.data = formatingDatatable(result.data)
fnCallback(result)
lastQuery = aoData;
} else {
$('#datatable_processing').css("visibility","hidden");
swal({ title: "Tidak ada hasil", type: "info"});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
swal({ title: manager.getAjaxError(XMLHttpRequest), type: "error"});
$('#datatable_processing').css("visibility","hidden");
$('.load__overlay').hide();
},
beforeSend: function() {
$('#datatable_processing').css("visibility","visible");
$('.load__overlay').show();
},
complete: function() {
$('#datatable_processing').css("visibility","hidden");
$('.load__overlay').hide();
}
});
}
});
}
function redraw() {
$("#datatable").dataTable().fnClearTable();
}
function formatingDatatable(events) {
var result = [];
var uri_next;
$.each(events.location_products, function(i, productlocation) {
result.push({
id: productlocation.id,
location_id: productlocation.location_id,
product_id: productlocation.product_id,
status_str: productlocation.status_str,
actions:'<button class="btn btn-primary waves-effect waves-light m-b-5 btn-sm m-r-5 btn-sm detail-productlocation" data-target="#modal-event-productlocation-detail" data-toggle="modal" data-id="' + productlocation.id + '" product-id="' + productlocation.product_id + '" location-id="' + productlocation.location_id + '" status-str="' + productlocation.status_str + '"><i class="glyphicon glyphicon-list"></i> Details</button>'
});
})
$("#after_id_url").val(events.page.uri_next)
uri_next = events.page.uri_next
result.after_id_url = uri_next
return result
}
function initFilter() {
$("#filter-form").submit(function() {
url_data_source = '/event/productlocation/ajax?action=data_source';
if(oTable == null){
initDataSource("");
} else {
oTable.fnDraw();
}
return false;
});
}
$('#datatable_paginate').on('click', '#datatable_next', function() {
initDataSource("");
})
$('#datatable').on('click', '.detail-productlocation', function() {
$('.load__overlay').show();
$("#modal-event-productlocation-detail").remove();
$(this).removeAttr("data-target", "#modal-event-productlocation-detail");
$(this).removeAttr("data-toggle", "modal");
//var id = $(this).attr("data-id");
var dt = {
"id": $(this).attr("data-id"),
"product_id": $(this).attr("product-id"),
"location_id": $(this).attr("location-id"),
"status": $(this).attr("status-str"),
}
$.ajax({
"url": '/event/productlocation/ajax?action=show_dialog_details',
"type": 'GET',
"data": dt,
success: function (result) {
$('.load__overlay').hide();
$("body").append(result);
$(this).attr("data-target", "#modal-event-productlocation-detail");
$(this).attr("data-toggle", "modal");
$('#modal-event-productlocation-detail').modal('show');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('.load__overlay').hide();
swal({ title: manager.getAjaxError(XMLHttpRequest), type: "error", });
},
});
});
$(document).ready(function() {
//initDate();
initFilter();
//initCategoryList();
var after_id = "";
initDataSource(after_id);
});
})(window);
event-productlocation-update.js
function sendProductLocationData() {
var jsonData = {};
var formFields = $(":input");
jQuery.each(formFields, function(i, field) { //Accessing all the element of form and get Key and Value
var key = field.name; //Keyname of each Field
var elementid = field.id; //Id of each Field
elementid = "#" + elementid;
var value = $(elementid).val();
jsonData[key] = parseInt(value);
if (key == "status") {
if ($("#event_checkbox_status").is(':checked') == true) {
jsonData.status = 1;
} else {
jsonData.status = 0;
}
}
});
productlocationdetail = JSON.stringify(jsonData); //Creating json Object
$.ajax({
url: '/update/product/productlocation',
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: productlocationdetail,
"success": function(result) {
var message_error = result.message_error
if (message_error) {
$('#modal-event-productlocation-detail').css("visibility", "hidden")
swal({
title: message_error,
type: "error"
});
$('.modal-backdrop').remove();
} else {
$('#modal-event-productlocation-detail').css("visibility", "hidden")
swal({
title: "Product Location Updated Successfully",
type: "info"
});
$('.modal-backdrop').remove();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
swal({
title: manager.getAjaxError(XMLHttpRequest),
type: "error"
});
$('#modal-event-productlocation-detail').css("visibility", "hidden")
$('.modal-backdrop').remove();
$('.load__overlay').hide();
},
beforeSend: function() {
$('#modal-event-productlocation-detail').css("visibility", "visible")
$('.modal-backdrop').remove();
},
complete: function() {
swal({
title: "Product Location Updated Successfully",
type: "info"
});
$('#modal-event-productlocation-detail').css("visibility", "hidden")
$('.modal-backdrop').remove();
$('.load__overlay').hide();
}
});
}
There are a few way you could handle this.
One way you could handle this is to store the item/s in a variable in a jSON array.
When get confirmation back from the server that that the the update was successful you could then create function to update the dataTable with with this function.
function updateDataTable(dataTableObj,jsonArray)
/*
Clears and populates the dataTable with JSON array
*/
dataTableObj.clear();
jsonArray.forEach(function(row){
dataTableObj.row.add(row);
});
dataTableObj.draw();
}
The other way you could update the table is to create a route on your server that sends the jsonArray but this requires an additional request to the server.
Note: If you use the Ajax call be sure to invoke the function inside the the ajax callback function
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);