JqGrid trying to send large data from server to grid but getting:Error during serialization or deserialization using the JSON JavaScriptSerializer - json

I have a problem I am receiving large amount of data from the server and am then converting it to Json format, to be then viewed in JqGrid. It works for small amount of data say for example 200 rows but when doing this for 10000 rows it throws the following error
System.InvalidOperationException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property
I have tried using the javascript serializer and set it to maxjsonLenght = int32.MaxValue but still no luck
Following is my code please give me suggestions with examples how I can fix this? Thanks all!
GridConfig
public JqGridConfig(String db, String jobGroup, String jobName, String detailTable, String filterBatchControl, String filterDate, String filterTime, int page)
{
var entityhelper = new EntityHelper();
var s = new JsonSerializer();
try
{
//Populate Grid Model, Column Names, Grid Column Model, Grid Data
entityhelper.PopulateDetailGridInit(db, jobGroup, jobName, detailTable, filterBatchControl, filterDate, filterTime);
JqGridDetailAttributes = entityhelper.GridDetailAttributes;
JqGridDetailColumnNames = entityhelper.GridDetailColumnNames;
//JqGridDetailsColumnNamesForExport = entityhelper.GridDetailColumnNamesForExport;
JqGridDetailColumnModel = entityhelper.GridDetailColumnModel;
//Dynamic Data
JqGridDynamicDetailData = entityhelper.GridDetailData;
#region Column Model
foreach (KeyValuePair<String, JqGridColModel> kvp in entityhelper.GridDetailColumnModel)
{
s.Serialize(kvp.Key, kvp.Value.Attributes);
}
JqGridDetailColumnModelJson = s.Json();
#endregion
#region Concrete data. 1. List<dynamic> populated, 2. Convert to Json String, 3: Convert back to List<Detail>
JqGridDetailData = JsonSerializer.ConvertDynamicDetailsToJson(JqGridDynamicDetailData); // this is where the error occurs
}
catch (Exception ex)
{
//TODO: Logging
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
Json Serializer
public static IList<Detail> ConvertDynamicDetailsToJson(IList<dynamic> list)
{
if (list.Count == 0)
return new List<Detail>();
var sb = new StringBuilder();
var contents = new List<String>();
sb.Append("[");
foreach (var item in list)
{
var d = item as IDictionary<String, Object>;
sb.Append("{");
foreach (KeyValuePair<String, Object> kvp in d)
{
contents.Add(String.Format("{0}: {1}", "\"" + kvp.Key + "\"", JsonConvert.SerializeObject(kvp.Value)));
}
sb.Append(String.Join(",", contents.ToArray()));
sb.Append("},");
}
sb.Append("]");
//remove trailing comma
sb.Remove(sb.Length - 2, 1);
var jarray = JsonConvert.DeserializeObject<List<Detail>>(sb.ToString());
return jarray;
}
Controller that return Json result from server
public JsonResult DetailGridData(TheParams param)
{
dynamic config= "";
switch (param.JobGroup)
{
case "a":
config = new BLL.abcBLL().GetDetailGridData("rid", "desc", 1, 20, null,
param.FilterBatchControl,
param.JobName, param.DetailTable,
param.JobGroup, param.BatchDate,
param.Source);
break;
}
return Json(config, JsonRequestBehavior.AllowGet); // this reurns successfully json result
}
View where the Jqgrid exists and does not populate the grid
<script type="text/javascript">
var jobGroup = '#ViewBag.JobGroup';
var jobName = '#ViewBag.JobName';
var detailTable = '#ViewBag.DetailTable';
var filterBatchControl = '#ViewBag.FilterBatchControl';
var controlDate = '#ViewBag.ControlDate';
var controlTime = '#ViewBag.ControlTime';
var source = '#ViewBag.DetailSource';
var page = '#ViewBag.page';
function loadDetailData() {
var param = new Object();
param.BatchDate = controlDate;
param.BatchTime = controlTime;
param.JobGroup = jobGroup;
param.JobName = jobName;
param.DetailTable = detailTable;
param.FilterBatchControl = filterBatchControl;
param.Source = source;
param.page = page;
window.parent.loadingDetailsHeader();
$.ajax({
url: "/control/detailgriddata",
dataType: 'json',
type: 'POST',
data: param,
async: false,
success: function (response) {
try {
jgGridDetailColumnNames = response.JqGridDetailColumnNames;
//jqGridDetailColumnData = response.JqGridDetailData;
jqGridDetailColumnData = response.config;
$('#detailGrid').jqGrid('setGridParam', {colNames: jgGridDetailColumnNames});
$('#detailGrid').jqGrid('setGridParam', {data: jqGridDetailColumnData}).trigger('reloadGrid');
parent.loadingDetailsHeaderComplete();
}
catch(e) {
window.parent.loadingDetailsHeaderException(e.Message);
}
return false;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function exportdetails(date) {
var param = new Object();
param.db = source;
param.jobGroup = jobGroup;
param.jobName = jobName;
param.detailTable = detailTable;
param.filterBatchControl = filterBatchControl;
param.filterDate = date;
param.filterTime = "NULL";
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("ExportDetailsCsv", "Control")',
dataType: 'json',
data: $.toJSON(param),
async: false,
success: function (response) {
window.location.assign(response.fileName);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Details Export Exception: " + xhr.status);
}
});
}
//<![CDATA[
$(document).ready(function () {
'use strict';
$(window).resize(function () {
$("#detailGrid").setGridWidth($(window).width());
}).trigger('resize');
var dgrid = $("#detailGrid");
$('#detailGrid').jqGrid('clearGridData');
loadDetailData();
dgrid.jqGrid({
datatype: 'json',
data: jqGridDetailColumnData,
colNames: jgGridDetailColumnNames,
colModel: [ #Html.Raw(#ViewBag.ColModelDetail) ],
rowNum: 25,
rowList: [25, 50, 100],
pager: '#detailPager',
gridview: true,
autoencode: false,
ignoreCase: true,
viewrecords: true,
altrows: false,
autowidth: true,
shrinkToFit: true,
headertitles: true,
hoverrows: true,
height: 300,
onSelectRow: function (rowId) {
//This is a demo dialog with a jqGrid embedded
//use this as the base for viewing detail data of details
//$('#dialogGrid').dialog();
//gridDialog();
},
loadComplete: function (data) {},
gridComplete: function (data) {
//if (parseInt(data.records,10) < 50) {
$('#detailPager').show();
//} else {
//$('#detailPager').show();
//}
}
}).jqGrid('navGrid', '#detailPager', { edit: false, add: false, del: false, search: false }, {});
});
//]]>
</script>
<table id="detailGrid">
<tr>
<td />
</tr>
</table>
<div id="detailPager"></div>
<div id="dialogGrid"></div>

Probably you should consider to use server side paging instead of returning 10000 rows to the client? Server side paging of SQL data can be implemented much more effectively as client side paging (sorting of large non-indexed data in JavaScript program).
One more option which you have is the usage of another JSON serializer. For example it can be protobuf-net, ServiceStack.Text (see here too), Json.NET and other. In the way you can additionally improve performance of your application comparing with JavaScriptSerializer.

Related

trying to upload Image in mvc web api project using jquery ajax only

I am trying to upload Image but upon running my application my Image parameter is passing null, and I don't know why it is not picking up the file I attached
but in my browser console when I check my image file object that if it is attached or not, it shows that it does attach
but in my controller its passing null
my ajax code where I am passing the image file object,
$('.empOfficialDetails').click(function (ev) {
ev.preventDefault();
var data = new Object();
data.UserName = $('#username').val();
data.UPassword = $('#userpass').val();
data.OfficialEmailAddress = $('#officialemail').val();
data.Departments = $('#departments :selected').text();
data.Designation = $('#designation :selected').text();
data.RoleID = $('#role').val();
data.Role = $('#role :selected').text();
data.ReportToID = $('#reportToID').val();
data.ReportTo = $('#reportTo :selected').text();
data.JoiningDate = $('#joindate').val();
data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
data.IsActive = $('#isActive :selected').val() ? 1 : 0;
data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
data.DateofPermanancy = $('#permanantdate').val();
data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
data.HiredbyReferenceName = $('#refePersonName').val();
data.BasicSalary = $('#basicSalary').val();
data.CurrentPicURL = $('.picture')[0].files; //this is my image file object
//data.EmpID = $('.HiddenID').val();
if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(data),
enctype: 'multipart/form-data',
beforeSend: function () {
$("#dvRoomsLoader").show();
},
complete: function () {
$("#dvRoomsLoader").hide();
},
success: function (data) {
var ID = parseInt(data);
if (ID > 0) {
//var id = data;
$(".HiddenID").val(data);
//var id = $(".HiddenID").val();
$('#official').css('display', 'block');
$('#official').html("Employees Official details added successfully...!");
$('#official').fadeOut(25000);
$("#dvRoomsLoader").show();
$('.empOfficialDetails').html("Update <i class='fa fa-angle-right rotate-icon'></i>");
}
else {
$('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
}
},
error: function (ex) {
alert("There was an error while submitting employee data");
alert('Error' + ex.responseXML);
alert('Error' + ex.responseText);
alert('Error' + ex.responseJSON);
alert('Error' + ex.readyState);
alert('Error' + ex.statusText);
}
});
}
return false;
});
but in controller on running the code it passes null
public void EmployeeImage(HttpPostedFileBase file)
{
var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
var fileName = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
byte[] bytes;
using (BinaryReader br = new BinaryReader(file.InputStream))
{
bytes = br.ReadBytes(file.ContentLength);
}
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
string myfile = name + "_" + ext; //appending the name with id
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/assets/img/profiles/employeeImages"), myfile); // store the file inside ~/project folder(Img)
file.SaveAs(path);
}
}
public int Emp_OfficialDetails(Employee emp)
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
var con = DB.getDatabaseConnection();
SqlCommand com = new SqlCommand("sp_InsEmpOfficialDetails", con);
com.CommandType = CommandType.StoredProcedure;
#region Employee Official Details Insert Code block
com.Parameters.AddWithValue("#UserName", emp.UserName);
com.Parameters.AddWithValue("#pass", emp.UPassword);
com.Parameters.AddWithValue("#OfficialEmailAddress", emp.OfficialEmailAddress);
com.Parameters.AddWithValue("#Department", emp.Departments);
com.Parameters.AddWithValue("#Role", emp.Role);
com.Parameters.AddWithValue("#IsAdmin", Convert.ToBoolean(emp.IsAdmin));
com.Parameters.AddWithValue("#Designation", emp.Designation);
com.Parameters.AddWithValue("#ReportToID", emp.ReportToID);
com.Parameters.AddWithValue("#ReportTo", emp.ReportTo);
com.Parameters.AddWithValue("#JoiningDate", Convert.ToDateTime(emp.JoiningDate));
com.Parameters.AddWithValue("#IsPermanent", Convert.ToBoolean(emp.IsPermanent));
com.Parameters.AddWithValue("#DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
com.Parameters.AddWithValue("#IsActive", Convert.ToBoolean(emp.IsActive));
com.Parameters.AddWithValue("#HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
com.Parameters.AddWithValue("#HiredbyReferenceName", emp.HiredbyReferenceName);
com.Parameters.AddWithValue("#BasicSalary", emp.BasicSalary);
com.Parameters.AddWithValue("#CurrentPicURL", emp.CurrentPicURL);
#endregion
var file = emp.CurrentPicURL;
EmployeeImage(file);
var ID = com.ExecuteScalar();
com.Clone();
return Convert.ToInt32(ID);
}
and in my model class my Image datatype is as
public HttpPostedFileBase CurrentPicURL { get; set; }
I have no Idea what I am doing wrong If anyone who knows about this, your help is highly appreciated my friend
You can't use JSON.stringify to upload a file via AJAX. You need to use the FormData class.
Sending files using a FormData object | MDN
const data = new FormData();
data.append("UserName", $('#username').val());
data.append("UPassword", $('#userpass').val());
...
const file = $('.picture')[0].files[0];
data.append("CurrentPicURL", file, file.name);
...
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
data: data,
processData: false,
contentType: false,
beforeSend: function () {
...
NB: Unless you need to support Internet Explorer, you might want to use the Fetch API instead of AJAX. This can be much simpler, particularly when combined with async and await.

Transform Request to Autoquery friendly

We are working with a 3rd party grid (telerik kendo) that has paging/sorting/filtering built in. It will send the requests in a certain way when making the GET call and I'm trying to determine if there is a way to translate these requests to AutoQuery friendly requests.
Query string params
Sort Pattern:
sort[{0}][field] and sort[{0}][dir]
Filtering:
filter[filters][{0}][field]
filter[filters][{0}][operator]
filter[filters][{0}][value]
So this which is populated in the querystring:
filter[filters][0][field]
filter[filters][0][operator]
filter[filters][0][value]
would need to be translated to.
FieldName=1 // filter[filters][0][field]+filter[filters][0][operator]+filter[filters][0][value] in a nutshell (not exactly true)
Should I manipulate the querystring object in a plugin by removing the filters (or just adding the ones I need) ? Is there a better option here?
I'm not sure there is a clean way to do this on the kendo side either.
I will explain the two routes I'm going down, I hope to see a better answer.
First, I tried to modify the querystring in a request filter, but could not. I ended up having to run the autoqueries manually by getting the params and modifying them before calling AutoQuery.Execute. Something like this:
var requestparams = Request.ToAutoQueryParams();
var q = AutoQueryDb.CreateQuery(requestobject, requestparams);
AutoQueryDb.Execute(requestobject, q);
I wish there was a more global way to do this. The extension method just loops over all the querystring params and adds the ones that I need.
After doing the above work, I wasn't very happy with the result so I investigated doing it differently and ended up with the following:
Register the Kendo grid filter operations to their equivalent Service Stack auto query ones:
var aq = new AutoQueryFeature { MaxLimit = 100, EnableAutoQueryViewer=true };
aq.ImplicitConventions.Add("%neq", aq.ImplicitConventions["%NotEqualTo"]);
aq.ImplicitConventions.Add("%eq", "{Field} = {Value}");
Next, on the grid's read operation, we need to reformat the the querystring:
read: {
url: "/api/stuff?format=json&isGrid=true",
data: function (options) {
if (options.sort && options.sort.length > 0) {
options.OrderBy = (options.sort[0].dir == "desc" ? "-" : "") + options.sort[0].field;
}
if (options.filter && options.filter.filters.length > 0) {
for (var i = 0; i < options.filter.filters.length; i++) {
var f = options.filter.filters[i];
console.log(f);
options[f.field + f.operator] = f.value;
}
}
}
Now, the grid will send the operations in a Autoquery friendly manner.
I created an AutoQueryDataSource ts class that you may or may not find useful.
It's usage is along the lines of:
this.gridDataSource = AutoQueryKendoDataSource.getDefaultInstance<dtos.QueryDbSubclass, dtos.ListDefinition>('/api/autoQueryRoute', { orderByDesc: 'createdOn' });
export default class AutoQueryKendoDataSource<queryT extends dtos.QueryDb_1<T>, T> extends kendo.data.DataSource {
private constructor(options: kendo.data.DataSourceOptions = {}, public route?: string, public request?: queryT) {
super(options)
}
defer: ng.IDeferred<any>;
static exportToExcel(columns: kendo.ui.GridColumn[], dataSource: kendo.data.DataSource, filename: string) {
let rows = [{ cells: columns.map(d => { return { value: d.field }; }) }];
dataSource.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
//push single row for every record
rows.push({
cells: _.map(columns, d => { return { value: data[i][d.field] } })
})
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: _.map(columns, d => { return { autoWidth: true } }),
// Title of the sheet
title: filename,
// Rows of the sheet
rows: rows
}
]
});
//save the file as Excel file with extension xlsx
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: filename });
})
}
static getDefaultInstance<queryT extends dtos.QueryDb_1<T>, T>(route: string, request: queryT, $q?: ng.IQService, model?: any) {
let sortInfo: {
orderBy?: string,
orderByDesc?: string,
skip?: number
} = {
};
let opts = {
transport: {
read: {
url: route,
dataType: 'json',
data: request
},
parameterMap: (data, type) => {
if (type == 'read') {
if (data.sort) {
data.sort.forEach((s: any) => {
if (s.field.indexOf('.') > -1) {
var arr = _.split(s.field, '.')
s.field = arr[arr.length - 1];
}
})
}//for autoquery to work, need only field names not entity names.
sortInfo = {
orderByDesc: _.join(_.map(_.filter(data.sort, (s: any) => s.dir == 'desc'), 'field'), ','),
orderBy: _.join(_.map(_.filter(data.sort, (s: any) => s.dir == 'asc'), 'field'), ','),
skip: 0
}
if (data.page)
sortInfo.skip = (data.page - 1) * data.pageSize,
_.extend(data, request);
//override sorting if done via grid
if (sortInfo.orderByDesc) {
(<any>data).orderByDesc = sortInfo.orderByDesc;
(<any>data).orderBy = null;
}
if (sortInfo.orderBy) {
(<any>data).orderBy = sortInfo.orderBy;
(<any>data).orderByDesc = null;
}
(<any>data).skip = sortInfo.skip;
return data;
}
return data;
},
},
requestStart: (e: kendo.data.DataSourceRequestStartEvent) => {
let ds = <AutoQueryKendoDataSource<queryT, T>>e.sender;
if ($q)
ds.defer = $q.defer();
},
requestEnd: (e: kendo.data.DataSourceRequestEndEvent) => {
new DatesToStringsService().convert(e.response);
let ds = <AutoQueryKendoDataSource<queryT, T>>e.sender;
if (ds.defer)
ds.defer.resolve();
},
schema: {
data: (response: dtos.QueryResponse<T>) => {
return response.results;
},
type: 'json',
total: 'total',
model: model
},
pageSize: request.take || 40,
page: 1,
serverPaging: true,
serverSorting: true
}
let ds = new AutoQueryKendoDataSource<queryT, T>(opts, route, request);
return ds;
}
}

Kendo UI - JSON Response for - Grid using Remote Data Source W/Server Grouping & Server Aggregates

I have a project in which I'm using the KendoUI Grid using the server to get the data instead of locally.
I'm not sure what the JSON response should be from my server to get grouping to work however. My goal is when the user drags a column to the grouping header that I know what kind of JSON response to give back so the GRID groups by that column and any other columns that might be added to that header.
Given the image above, how do I create a JSON response to fulfill it (so its showing what its supposed to grouped)? I get I have to do this on my own on the server but not sure how JSON needs to be formated. Furthermore if I want to show a 'count' field next to the groups when they are created so I know how many items are in each group (which I believe is the aggregate?)
My current grid codes looks like the following:
<div id="grid" style="height:100%;"></div>
<script>
$(window).on("resize", function() {
kendo.resize($("#grid"));
});
var crudServiceBaseUrl = "/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/companies",
dataType: "json",
type: "POST"
},
update: {
url: crudServiceBaseUrl + "/companies/update",
dataType: "json",
type: "POST"
},
destroy: {
url: crudServiceBaseUrl + "/companies/destroy",
dataType: "json",
type: "POST"
},
create: {
url: crudServiceBaseUrl + "/companies/create",
dataType: "json",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
error: function (e) {
/* the e event argument will represent the following object:
{
errorThrown: "custom error",
errors: ["foo", "bar"]
sender: {... the Kendo UI DataSource instance ...}
status: "customerror"
xhr: null
}
*/
//alert("Status: " + e.status + "; Error message: " + e.errorThrown);
console.log("Status: " + e.status + "; Error message: " + e.errorThrown);
console.log("Errors: " + e.errors.join("; "));
},
autoSync: false,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
serverGrouping: true,
serverAggregates: true,
pageSize: 20,
columnResizeHandleWidth: 6,
schema: {
total: "itemCount",
data: "items",
groups: "groups",
aggregates: "aggregates",
group: {
field: "phone", aggregates: [{ field: "phone", aggregate: "count" }]
},
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } },
phone: {
type: "string",
validation: {
required: true,
phonerule: function(e){
if (e.is("[data-phonerule-msg]"))
{
var input = e.data('kendoMaskedTextBox');
//If we reached the end of input then it will return -1 which means true, validation passed
//Otherwise it won't === -1 and return false meaning all the characters were not entered.
return input.value().indexOf(input.options.promptChar) === -1;
}
return true; //return true for anything else that is not data-phonerule-msg
}
}
},
email: { type: "string", validation: { required: true, email:true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
groupable: true,
sortable: {
mode: "multiple",
allowUnsort: true
},
selectable: "multiple cell",
allowCopy:true,
toolbar: ["create","excel"],
excel: {
fileName: "Kendo UI Grid Export.xlsx",
//Below is only used as fallback for old browsers without support
proxyURL: "//demos.telerik.com/kendo-ui/service/export",
filterable: true
},
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
reorderable: true,
resizable: true,
columnMenu: true,
filterable: true,
editable: "popup",
mobile: true,
columns: [
{
field: "name",
title: "Company Name",
aggregates: ["count"],
groupFooterTemplate: "Count: #=count#"
},
{
field: "phone",
title: "Phone",
editor: function(container, options){
//pattern="[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}"
var input = $('<input type="tel" data-phonerule-msg="Invalid Phone Number!" class="k-textbox" required />');
input.attr("name", options.field);
input.kendoMaskedTextBox({
mask: "(999) 000-0000"
});
input.appendTo(container);
},
aggregates: ["count"],
groupFooterTemplate: "Count: #=count#"
},
{
field: "email",
title: "Email",
editor: function(container, options){
var input = $('<input type="email" data-email-msg="Invalid email!" class="k-textbox" required/>');
input.attr("name", options.field);
input.appendTo(container);
},
aggregates: ["count"],
groupFooterTemplate: "Count: #=count#"
},
{
command: ["edit", "destroy"],
title: "Operations",
width: "240px"
}
],
});
</script>
My current code that generates the demo javascript via Symfony 3.0 is below in..
DefaultController.php
/**
* #Route("/api/companies", name="api_companies_read")
*/
public function apiCompaniesReadAction(Request $request)
{
$data["itemCount"] = "7";
// $tdata["field"] = "";
// $tdata["value"] = "";
// $tdata["items"] = "hey";
// $data["groups"][] = $tdata;
$tdata["id"] = "1";
$tdata["name"] = "Joe";
$tdata["phone"] = "(714)475-8651";
$tdata["email"] = "Joe#whatever.com";
$data["items"][] = $tdata;
$tdata["id"] = "2";
$tdata["name"] = "Rachel";
$tdata["phone"] = "(563)812-4184";
$tdata["email"] = "rachel#yahoo.com";
$data["items"][] = $tdata;
$tdata["id"] = "3";
$tdata["name"] = "John";
$tdata["phone"] = "(563)812-4184";
$tdata["email"] = "John#yahoo.com";
$data["items"][] = $tdata;
$tdata["id"] = "4";
$tdata["name"] = "Richard";
$tdata["phone"] = "(563)812-4184";
$tdata["email"] = "John#yahoo.com";
$data["items"][] = $tdata;
$tdata["id"] = "5";
$tdata["name"] = "Sister";
$tdata["phone"] = "(563)812-4184";
$tdata["email"] = "John#yahoo.com";
$data["items"][] = $tdata;
$tdata["id"] = "6";
$tdata["name"] = "Brother";
$tdata["phone"] = "(563)812-4184";
$tdata["email"] = "Brother#yahoo.com";
$data["items"][] = $tdata;
$tdata["id"] = "7";
$tdata["name"] = "Sibling";
$tdata["phone"] = "(563)812-4184";
$tdata["email"] = "Sibling#yahoo.com";
$data["items"][] = $tdata;
// schema: {
// total: "total",
// model: {
// id: "CompanyID",
// fields: {
// CompanyID: { editable: false, nullable: true },
// Name: { validation: { required: true } },
// Phone: { type: "string" },
// Email: { type: "string" }
// }
// }
// }
// replace this example code with whatever you need
return new JsonResponse($data);
}
The current JSON it creates looks like this.
JSON
{"itemCount":"7","items":[{"id":"1","name":"Joe","phone":"(714)475-8651","email":"Joe#whatever.com"},{"id":"2","name":"Rachel","phone":"(563)812-4184","email":"rachel#yahoo.com"},{"id":"3","name":"John","phone":"(563)812-4184","email":"John#yahoo.com"},{"id":"4","name":"Richard","phone":"(563)812-4184","email":"Richard#yahoo.com"},{"id":"5","name":"Sister","phone":"(563)812-4184","email":"Sister#yahoo.com"},{"id":"6","name":"Brother","phone":"(563)812-4184","email":"Brother#yahoo.com"},{"id":"7","name":"Sibling","phone":"(563)812-4184","email":"Sibling#yahoo.com"}]}
I found an article here that looks close to what I want just hard to understand. This might also help.
I created JSFiddle that can be played around with, just needs to be supplied valid data.
Update
I got server paging to work! The first major change is on the transport for the datasource you have to change the parameterMap to send json so you can access what its trying to tell your server to change.
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/companies",
dataType: "json",
type: "POST"
},
update: {
url: crudServiceBaseUrl + "/companies/update",
dataType: "json",
type: "POST"
},
destroy: {
url: crudServiceBaseUrl + "/companies/destroy",
dataType: "json",
type: "POST"
},
create: {
url: crudServiceBaseUrl + "/companies/create",
dataType: "json",
type: "POST"
},
parameterMap: function(options, operation) {
return kendo.stringify(options);
}
},
My datasource looks like above, but you could adjust to your needs. Next my php file below.
PHP
/companies
/**
* #Route("/api/companies", name="api_companies_read")
*/
public function apiCompaniesReadAction(Request $request)
{
$request_body = file_get_contents('php://input');
$json = json_decode($request_body);
//Based on the JSON Payload response adjust the search in the database
if($json){
$page = $json->page;
$pageSize = $json->pageSize;
$skip = $json->skip;
$take = $json->take;
}else{
$page = 1;
$pageSize = 20;
$skip = 1;
$take = 1;
}
$repository = $this->getDoctrine()->getRepository('AppBundle:Company');
/*
findBy(
array $criteria,
array $orderBy = null,
integer|null $limit = null,
integer|null $offset = null
)
*/
$company_total = $repository->findAll();
$company_records = $repository->findBy(array(),array(),$pageSize,($page-1)*$pageSize);
$data["total"] = count($company_total);
foreach($company_records as $company){
$temp["id"] = $company->getId();
$temp["name"] = $company->getName();
$temp["phone"] = $company->getPhone();
$temp["email"] = $company->getEmail();
$data["data"][] = $temp;
}
//converts data to JSON
return new JsonResponse($data);
}
Please remember the above is a Symfony 3.0 php implementation using annotations to set the route. The important part in that code is.
$request_body = file_get_contents('php://input');
$json = json_decode($request_body);
//Based on the JSON Payload response adjust the search in the database
if($json){
$page = $json->page;
$pageSize = $json->pageSize;
$skip = $json->skip;
$take = $json->take;
}else{
$page = 1;
$pageSize = 20;
$skip = 1;
$take = 1;
}
The file_get_contents('php://input'); gets the javascript object that the KendoUI control sends back.
UPDATE # 3 Got Server Sorting Working!
Below is an example implementaiton using Symfony 3.0 and Doctrine to do Server Sorting!
PHP
/**
* #Route("/api/companies", name="api_companies_read")
*/
public function apiCompaniesReadAction(Request $request)
{
$request_body = file_get_contents('php://input');
$json = json_decode($request_body);
//print_r($json);
//default parameters in case of error.
$page = 1;
$pageSize = 20;
$skip = 1;
$take = 1;
$sort = array();
//Based on the JSON Payload response adjust the search in the database
if(isset($json)){
$page = $json->page;
$pageSize = $json->pageSize;
$skip = $json->skip;
$take = $json->take;
if(isset($json->sort)){
//"sort":[{"field":"name","dir":"asc"}]}:
foreach($json->sort as $sortObj){
$sort[$sortObj->field] = $sortObj->dir;
}
}
}
$repository = $this->getDoctrine()->getRepository('AppBundle:Company');
/*
findBy(
array $criteria,
array $orderBy = null,
integer|null $limit = null,
integer|null $offset = null
)
*/
$company_total = $repository->findAll();
$company_records = $repository->findBy(array(),$sort,$pageSize,($page-1)*$pageSize);
$data["total"] = count($company_total);
foreach($company_records as $company){
$temp["id"] = $company->getId();
$temp["name"] = $company->getName();
$temp["phone"] = $company->getPhone();
$temp["email"] = $company->getEmail();
$data["data"][] = $temp;
}
//converts data to JSON
return new JsonResponse($data);
}
That first link is spot on. I had to export data from a grid to pdf and excel adhering to the grid grouping. I finally figured out the semantics. The grid has columns and data objects which you can get through grid calls. The data object holds the grouping information. Here is the processing operation.
In a nutshell, you have to recursively iterate the data object tpo determine the grouping. For each element in the data you need to inspect if the data[x].value exists. If it exists then it is a group object with child data. If it does not exists then you use the normal data[row][column].field to get to the child data. The trick here is to call a recurisive function for each point where dat[0].value has data and finally process the data[row][column] on the unwind.
Below is a js function you can use to inspect the Grid's json dta. I would add a group or two to your grid and see the difference between the data with/without grouping applied and that should be what you need to add to your data....I think you pretty much add data as data={[[],[]]}unless it is a group, then it is data={[value='groupName',{[],[]}]}.
function showData(gridName) {
var grid = $('#' + gridName).data('kendoGrid');
var data = grid.dataSource.data().toJSON();
console.log(data);
}

Json Post size limit increase in MVC 4

I have seen & tried a lot of codes to increase the JSON limit like in
1. web.config
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647"/>
</webServices>
</scripting>
</system.web.extensions>
2.JSonControllerFactory
public sealed class CustomJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
IDictionary<string, object> d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
IList l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
Down here in GetDeserializedObject() i am getting bodytext as empty and unable to set the max property.
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue; //increase MaxJsonLength. This could be read in from the web.config if you prefer
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
}
script [down data: jQuery("#geomaster").serialize() contains data. If it is below 100 points the data is saving successfully. if it crosses 100 points, not hitting the controller SaveGeodata method(i mean not posting to controller)].
jQuery.ajax({
type: "GET",
url: "SaveGeodata",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: jQuery("#geomaster").serialize(),
success: function (data) {
alert("Geofence Created Successfully");
},
error: function (msg) {
alert("Error");
}
});
Is there any way where i can attach the maxJsonSize property in script itself.
Any other possible means which could help in posting max data to controller is really thankful.

How to Access each elements in the following json output

Here is my j-son output and i want to access inner elements element.
how should i do that?
i have tried to access them in the following way
data[10];
but it didn't worked
public JsonResult ShowEventsList()
{
using (EventSchedularEntities db = new EventSchedularEntities())
{
var EventsList = from evnt in db.Events
select new
{
id = evnt.EventID,
Subject = evnt.EventName,
Description = evnt.EventDesc,
StartTime = evnt.EventDateBegin,
EndTime = evnt.EventDateEnd,
Color = evnt.Importance,
};
List<object[]> LstEvents = new List<object[]>();
foreach (var ev in EventsList)
{
LstEvents.Add(new object[] { ev.id, ev.Subject, ev.Description,DateTime.Parse(ev.StartTime.ToString()).ToString("M/dd/yyyy hh:mm").Replace("-", "/"), DateTime.Parse(ev.EndTime.ToString()).ToString("M/dd/yyyy hh:mm").Replace("-", "/"), ev.Color });
}
return Json( LstEvents, JsonRequestBehavior.AllowGet);
}
}
$.ajax({
type: "POST",
url: "../EventScheduler/ShowEventsList",
datatype: "json",
success: function (result)
{
var data = JSON.parse(result);
alert(data);
}