I am working with a Datatables.Net plug into an internal web application to my company.
The issue Im facing is in the variable JSON, I can see that I have returned a JSON response, and it is valid according to JSONLint, but I cannot get the information out of the JSON array into my tables despite following all the examples on Datatables and searching their help site.
please see my code and let me know why this isn't populating the tables.
function populateTable(json, tableId) {
var id = 'table_' + tableId;
console.log("Columns In");
//console.log("table id: " + id + " JSON Response: " + json);
try {
var table = $('#' + id).DataTable({
"data": json.d,
"deferRender": true,
"columns:": [
{ "data ": "CaseHandlerStaffNumber" },
{ "data ": "RiskProfileText" },
{ "data ": "AssignedCheckerStaffNumber" },
{ "data ": "FeedbackUserStaffNumber" },
{ "data ": "ComplaintRef" },
{ "data ": "ChildComplaintRef" },
{ "data ": "CaseTypeText" },
{ "data ": "CheckGrade" }
]
});
} catch (e) {
}
try {
table.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
} catch (e) {
console.log("Error detected: " + e);
console.log(e);
}
}
-- edit --
this is an example of my JSON data.
{
"data": [{
"CaseHandlerStaffNumber": "12345678",
"RiskProfileText": "Low Risk FOS",
"AssignedCheckerStaffNumber": "77665544",
"FeedbackUserStaffNumber": null,
"ComplaintRef": "999999",
"ChildComplaintRef": "2333",
"CaseTypeText": "FOS Submission",
"CheckGrade": "Ungraded"
}]
}
also, this is how I am producing the JSON
[System.Web.Services.WebMethod()]
public static object GetDataTables(string checkId, int userId)
{
List<string> listOfColumnns = new List<string>();
listOfColumnns.Add("CaseHandlerStaffNumber");
listOfColumnns.Add("RiskProfileText");
listOfColumnns.Add("AssignedCheckerStaffNumber");
listOfColumnns.Add("FeedbackUserStaffNumber");
listOfColumnns.Add("ComplaintRef");
listOfColumnns.Add("ChildComplaintRef");
listOfColumnns.Add("CaseTypeText");
listOfColumnns.Add("CheckGrade");
int checkStatusId = Convert.ToInt32(checkId.Replace("hidJson_tbl_", ""));
TeamChecks tc = new TeamChecks();
DataTable dtMc = default(DataTable);
dtMc = tc.Get_DatatableFor_GridView(userId, checkStatusId);
DataTable dt = new DataTable();
foreach (void colName_loopVariable in listOfColumnns) {
colName = colName_loopVariable;
dt.Columns.Add(string.Format("{0}", colName));
}
foreach (void row_loopVariable in dtMc.Rows) {
row = row_loopVariable;
dt.Rows.Add(row("CaseHandlerStaffNumber"), row("RiskProfileText"), row("AssignedCheckerStaffNumber"), row("FeedbackUserStaffNumber"), row("ComplaintRef"), row("ChildComplaintRef"), row("CaseTypeText"), row("CheckGrade"));
}
string jsonResult = null;
jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
jsonResult = jsonResult.Replace("[{", "{\"data\" :[{").Replace("}]", "}]}");
return jsonResult;
}
First, make sure you remove extra space at the end of "data" property, e.g.
{ "data": "caseHandlerStaffNumber" },
If your data is in a form of array of objects you need to use "title" property as defined here https://datatables.net/examples/data_sources/js_array.html e.g.
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
{ title: "Extn." },
{ title: "Start date" },
{ title: "Salary" }
]
} );
If you're using nuget package, it internally uses Json.NET serializer with an option to lower case first letter of the data set. So, you just need to use lower case when specifying data as follows:
{ "data": "caseHandlerStaffNumber" },
{ "data": "riskProfileText" },
{ "data": "assignedCheckerStaffNumber" },
{ "data": "feedbackUserStaffNumber" },
{ "data": "complaintRef" },
{ "data": "childComplaintRef" },
{ "data": "caseTypeText" },
{ "data": "checkGrade" }
Related
enter image description hereI have this controller GetList and i am using Linq.Dynamic to filter for fields in the table be searched and this uses dataTable for server side processing. Who can help me to resolve this problem? Below is my logic and line where this error is thrown;
[\[HttpPost\]
public ActionResult GetList()
{
//Server side Parameter.
int start = Convert.ToInt32(Request\["start"\]);
int length = Convert.ToInt32(Request\["length"\]);
string searchValue = Request\["search\[value\]"\];
string sortColumnName = Request\["columns\[" + Request\["order\[0\]\[column\]"\] + "\]\[name\]"\];
string sortDirection = Request\["order\[0\]\[dir\]"\];
using (eNtsaOnlineRegistrationDBContext db = new eNtsaOnlineRegistrationDBContext())
{
IQueryable<TblEventsManagements> empList = db.TblEventsManagements;
int totalrows = empList.Count();
int totalrowsafterfiltering = totalrows;
if (!string.IsNullOrEmpty(searchValue))
{
empList = empList.Where(x => x.TrainingType.Contains(searchValue) || x.TrainingDescription.Contains(searchValue) || x.Price.ToString().Contains(searchValue.ToLower())
|| x.Venue.Contains(searchValue) || x.Facilitator.Contains(searchValue) || x.WhoAttend.Contains(searchValue) || x.Rsvp.Contains(searchValue));
}
empList = empList.OrderBy(sortColumnName + "" + sortDirection).Skip(start).Take(length);
return Json(new { data = empList, draw = Request\["draw"\], recordsTotal = totalrows, recordsFiltered = totalrowsafterfiltering }, JsonRequestBehavior.AllowGet);
}
}][1]
I forgot to put my Ajax call, i thought at first the issue was missing field from my table. Now i am getting field or type 'TrainingTypeasc' is not exist, well it does on my table from the database. Where can i improve this logic mates? Please help.
<script>
$(document).ready(function () {
$("#EventManagementTable").DataTable({
"ajax": {
"url": "/Dashboard/GetList",
"type": "POST",
"datatype":"json"
},
"columns": [
{"data": "TrainingType", "name": "TrainingType"},
{ "data": "TrainingDescription", "name": "TrainingDescription" },
{ "data": "Price", "name": "Price" },
{ "data": "Venue", "name": "Venue" },
{ "data": "Facilitator", "name": "Facilitator" },
{ "data": "WhoAttend", "name": "WhoAttend" },
{"data": "RSVP", "name": "RSVP"},
],
"serverSide": "true",
"order":[0,"asc"],
"processing": "true",
"language": {
"processing":"processing... please wait"
}
});
});
Replace this :
empList = empList.OrderBy(sortColumnName + "" + sortDirection).Skip(start).Take(length);
with this:
empList = empList.OrderByPropertyName(sortColumnName,sortDirection).Skip(start).Take(length)
and add this to your project:
using System.Collections.Generic;
using System.Linq;
namespace "YourNameSpace"
{
public static class ListExtension
{
public static IOrderedEnumerable<T> OrderByPropertyName<T>(this ICollection<T> list, string sortColumnName, string sortDirection)
{
var type = typeof(T);
var property = sortColumnName == "" ? type.GetProperties().FirstOrDefault() : type.GetProperties().Where(p => p.Name == sortColumnName).FirstOrDefault();
return sortColumnName == "asc" ? list.OrderBy(p => property.GetValue(p)) : list.OrderByDescending(p => property.GetValue(p));
}
}
}
I want to retrieve all the documents of a collection from mongoDB in C# .Net Web API. Below code is working fine but It is returning BsonDocument
var client = new MongoClient(connectionString);
var db = client.GetDatabase("STRDB");
var mongoCollection = db.GetCollection<BsonDocument>(collection);
var documents = mongoCollection.AsQueryable();
return Ok(documents);
From above code I am getting data in below format (After JSON.stringify() in angular)
[
[
{
"name":"_id",
"value":"5de9f351baca28556c6a4b71"
},
{
"name":"Name",
"value":"Harsha"
},
{
"name":"Age",
"value":20
},
{
"name":"Gender",
"value":"M"
},
{
"name":"Skills",
"value":[
{
"name":"Java",
"value":""
},
{
"name":"Mule",
"value":true
},
{
"name":"Angular",
"value":""
}
]
}
],
[
{
"name":"_id",
"value":"5de9f358baca28556c6a4b72"
},
{
"name":"Name",
"value":"Anji"
},
{
"name":"Age",
"value":21
},
{
"name":"Gender",
"value":"M"
},
{
"name":"Skills",
"value":[
{
"name":"Java",
"value":""
},
{
"name":"Mule",
"value":true
},
{
"name":"Angular",
"value":true
}
]
}
]
]
How to receive it in proper JSON format OR how to convert this BSON document in JSON as I am unable to process this output.
Try the following, with conversion.
var client = new MongoClient(connectionString);
var db = client.GetDatabase("STRDB");
var mongoCollection = db.GetCollection<BsonDocument>(collection);
var documents = mongoCollection.AsQueryable();
return Ok(documents.ToList().ConvertAll(BsonTypeMapper.MapToDotNetValue));
Suppose i have
Json1:
[
{
"key":"1",
"val2":"5",
"val3":"short",
"val4":"pant",
"val5":"blue",
},
{
"key":"2",
"val2":"6",
"val3":"long",
"val4":"shirt",
"val5":"red",
}
]
And I have Json2:
[
{
"key":"1",
"qty":"3"
},
{
"key":"2",
"qty":"6",
}
]
I would like to have the following results
Json3:
[
{
"key":"1",
"val2":"5",
"val3":"short",
"val4":"pant",
"val5":"blue",
"qty":"3"
},
{
"key":"2",
"val2":"6",
"val3":"long",
"val4":"shirt",
"val5":"red",
"qty":"6"
}
]
is there a way to combine using a key in my case I would want to use the "key" as the key to know what qty to place where.
I'm trying to achieve a similar effect of an inner join to combine them that way.
Thanks,
var json1 = '[' +
'{ "key":"1" , "val2":"5", "val3":"short", "val4":"pant","val5":"blue" }, ' +
'{ "key":"2", "val2":"6", "val4":"shirt", "val5":"red" } ]';
var json2 = '[' +
'{ "key":"1", "qty":"3"}, ' +
'{ "key":"2", "qty":"6" } ]';
var obj1 = JSON.parse(json1);
var obj2 = JSON.parse(json2);
for(var i in obj1) {
if(obj1[i].key === obj2[i].key) {
obj1[i].qty = obj2[i].qty;
}
}
console.log(obj1);
Using Json.net's merge method:
var json1 = JArray.Parse(#"[
{
""key"":""1"",
""val2"":""5"",
""val3"":""short"",
""val4"":""pant"",
""val5"":""blue"",
},
{
""key"":""2"",
""val2"":""6"",
""val3"":""long"",
""val4"":""shirt"",
""val5"":""red"",
}
]");
var json2 = JArray.Parse(#"[
{
""key"":""1"",
""qty"":""3""
},
{
""key"":""2"",
""qty"":""6"",
}
]");
json1.Merge(json2, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Merge
});
I am trying to export data to excel file directly from datasource, I am able to export it to excel but the problem is the data are not sorted the way I want it to be nor group in the way I want it to be.
No matter what I do, the output is not sorted the way I want it to be, it is just as same as the way the data is retrieved from datasource.
Sample Input data:
|Celine|29|Female|
|Kian|25|Male|
|Juan|40|Male|
|Satia|25|Female|
|Kulim|50|Male|
|Liz|15|Female|
Sample Output in excel:
|Liz|15|Female|
|Satia|25|Female|
|Celine|29|Female|
|Kian|25|Male|
|Juan|40|Male|
|Kulim|50|Male|
Here is a snippet of code I used:
$(".export-excel").click(function () {
var from = new Date($("input#startDate").val()), to = new Date($("input#endDate").val());
var ds = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: webApiUrl +
"/data/getdata(startDateString='" +
(from.getFullYear() + "-" + (from.getMonth() + 1) + "-" + from.getDate()) +
"', endDateString='" + (to.getFullYear() + "-" + (to.getMonth() + 1) + "-" + to.getDate()) + "')",
dataType: "json"
},
parameterMap: function (options, data) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
var d = kendo.data.transports.odata.parameterMap(data);
delete paramMap.$inlinecount;
delete paramMap.$format;
paramMap.$count = true;
return paramMap;
}
},
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data['odata.count'];
},
errors: function (data) {
},
model: {
fields: {
Name: { type: "string" },
Age: { type: "string" },
Gender: {type:"string"}
}
},
group: {
field: "Gender"
}
},
sort: {
field: "Gender",
dir: "asc"
},
sortable: true,
pageable: true,
groupable: true,
filterable: true,
});
ds.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
rows.push({
cells: [
{ value: data[i].Name },
{ value: data[i].Age},
{ value: data[i].Gender}
]
})
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: [
// Column settings (width)
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true }
],
title: "Peaple_Report"
}
]
});
//save the file as Excel file with extension xlsx
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "Test.xlsx" });
});
});
Thank you in advanced.
.data() method holds the pristine data when not sorted or filtered ...
when you have applied any filter or sorting or grouping or paging ... you should read the data from .view() method ... that will give you the sorted/filtered data you are looking for ...
here is the documentation of .view() method - http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-view
I have a kendo grid in my application and i have added export to excel button to that kendo grid .
My question here is if select the small amount of data in kendo grid and when click on export button everything is working fine
but the problem is if select the large amount of data more than 1000 rows then the web page will become crash and it showing "Aw, Snap" Error
my environment : C#, Jquery, Kendo Grid
I have this code in my js
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
tableToExcel("table2excel");
it works fine when the data is small . but if the data is large more than 1000 it crashes the browser
I heard that Chrome can only handle HREF's that are roughly 2 million characters long. So can i handle this using Blob object ? if yes can somebody let me know how to use blob object in my case ?
Please help to resolve this issue .
It exports all data and custom selection using checkbox as well.
function excelExport() {
var exportAll = $('.selectrow').is(":checked");
var grid = $("#grid");
var rows = [{
cells: [
{ value: "column1" },
{ value: "column2" },
{ value: "column3" },
{ value: "column4" },
{ value: "column5" },
{ value: "column6" },
{ value: "column7" }
]
}];
if (exportAll) {
var dataDource = grid.getKendoGrid();
var trs = $("#grid").find('tr');
for (var i = 0; i < trs.length; i++) {
if ($(trs[i]).find(":checkbox").is(":checked")) {
var dataItem = dataDource.dataItem(trs[i]);
rows.push({
cells: [
{ value: dataItem.column1 },
{ value: dataItem.column2 },
{ value: dataItem.column3 },
{ value: dataItem.column4 },
{ value: dataItem.column5 },
{ value: dataItem.column6 },
{ value: dataItem.column7 }
]
})
}
}
}
else {
var dataSource = grid.data("kendoGrid").dataSource;
var trs = grid.find('tr');
for (var i = 1; i < dataSource._data.length; i++) {
var dataItem = dataSource._data[i];
rows.push({
cells: [
{ value: dataItem.column1 },
{ value: dataItem.column2 },
{ value: dataItem.column3 },
{ value: dataItem.column4 },
{ value: dataItem.column5 },
{ value: dataItem.column6 },
{ value: dataItem.column7 }
]
})
}
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: [
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true }
],
title: "Exported Data Result",
rows: rows
}
]
});
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "ExportedData" });
}