so I have a grid that uses loadonce set to true and rowTotal to spicify the number of rows returned. My database has about 200,000 records, however it seems to timeout if I set the return to that amount, I can only really load about 20,000 records without any problems. Is there a way to make it return everything from the database? My query I use to retrieve the values is
public IEnumerable<vwWell> GetAll()
{
return from e in db.vwWells
select e;
}
my web API code is
static readonly IWellRepository repository = new WellRepository();
WellsMigrationEntities db = new WellsMigrationEntities();
// GET api/values
public dynamic Get(string sidx, string sord, int page, int totalrows)
{
var wells = repository.GetAll() as IEnumerable<vwWell>;
var pageIndex = Convert.ToInt32(page) - 1;
var pageSize = totalrows;
var totalRecords = wells.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
wells = wells.Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalrows,
page = page,
records = totalRecords,
rows = wells.ToArray() //We need an array of objects for the rows
};
return jsonData;
}
and my grid code is
<script>
var API_URL = "http://localhost:41389/api/well";
jQuery("#gridMain").jqGrid({
url: API_URL,
datatype: "json",
mtype: 'GET',
loadonce: true,
gridview: true,
autowidth: true,
sortable: true,
viewrecords: true,
colNames: ['Id', 'APINumber', 'CountyName', 'LeaseName'],
colModel: [
{ name: 'WellKey', index: 'WellKey', width: 55, sorttype: "int", hidden: true},
{ name: 'APINumber', index: 'APINumber', width: 90, sorttype: "text" },
{ name: 'CountyName', index: 'CountyName', width: 100, sorttype: "text" },
{ name: 'LeaseName', index: 'LeaseName', width: 80, sorttype: "text" }
],
pager: '#pager3',
rowNum: 200,
rowTotal: 20000,
jsonReader: { repeatitems: false, id: "WellKey" },
rowList: [200, 300, 500],
sortname: 'WellKey',
sortorder: "desc",
caption: "JSON Example"
});
See how I have rowTotal set to 20,000, if I dont set that nothing returns, but it seems I am limited in the number of rows it is able to return.
Related
Just putting in a new grid, and everything seems to be working well, except for one thing. Using basic inline, it is sending a new incorrect key value for the column I have set with key: true. This is an auto-increment column in the database, so I just don't want to send any data for this column when ADDING, only for edit or delete is that required.
It is posting a parameter: row_id => jqg3 for the new key column and messing up my server script. So because adding the new row will auto-increment the row_id col, I don't need to send this.
How do I stop the jqGrid from sending this (row_id) index column value when saving a new added row?
free-jqgrid version is 4.14.0
$('#accts').jqGrid({
url:'/phpAJAX/Master/master_grid_v1.php',
editurl:'/phpAJAX/Master/master_grid_v1.php',
height: 'auto',
shrinkToFit: false,
width: 'auto',
datatype: 'xml',
mtype: 'POST',
postData:{
'arg1':'bol_acct'
},
colNames:[
'row_id',
'Customer',
'Trucker',
'Acct Num'
],
colModel:[
{name: 'row_id', hidden: true, key: true},
{name:'Customer', align: "center", editable: true},
{name: 'Trucker', align: "center"},
{name: 'Acct_Num', align: "center"}
],
sortname: 'Customer',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'Bill of Lading Accounts',
rowNum: 10000,
pager:true
}).jqGrid('inlineNav', {
addParams: {
addRowParams: { extraparam: {'arg1':'bol_acct', 'oper':'add'} }
},
editParams: {
extraparam: {
'arg1':'bol_acct', 'oper':'edit'
}
}
})
One can use serializeSaveData callback of inline editing to modify the data, which will be send during inline editing. You can add serializeSaveData callback via
inlineEditing: {
keys: true,
extraparam: { arg1: "bol_acct" },
serializeSaveData: function (postData) {
var newPostData = $.extend(true, {}, postData);
if (newPostData.oper === "add") {
delete newPostData.id; // delete id parameter
}
return newPostData;
}
}
My subgrid only shows the column headers but not not load the json data from the main grid. The columns are empty. I followed the tutorial on JQuery Grid-SubGrid for Parent-Child relation
but it does not work.
This is my javascript code:
jQuery().ready(function () {
var grid = jQuery("#shipment_grid");
var mainGridPrefix = "s_";
grid.jqGrid({
url: '${pageContext.request.contextPath}/getTruckShipmentJSONAction?truckId=' + <c:out value="${truckId}" />,
datatype: "json",
mtype: 'GET',
loadonce: true,
colNames: ['Lead Tracking #'],
colModel: [
{name: 'trackingNr', index: 'trackingNr', width: 100, align: 'left'}
],
rowNum: 10,
height: 230,
width: 700,
idPrefix: mainGridPrefix,
autoheight: true,
rowList: [10, 20, 30],
pager: jQuery('#shipment_grid_pager'),
sortname: 'trackingNr',
sortorder: "desc",
jsonReader: {
root: "records",
page: "page",
total: "total",
records: "rows",
repeatitems: false
},
viewrecords: true,
altRows: false,
gridview: true,
multiselect:true,
hidegrid: false,
shrinkToFit: true,
forceFit: true,
idPrefix: mainGridPrefix,
caption: "Shipments Overview",
subGrid: true,
beforeProcessing: function(data) {
//align 'Lead Tracking #' column header to the left
grid.jqGrid ('setLabel', 'trackingNr', '', {'text-align':'left'});
var rows = data.rows, l = rows.length, i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.shipUnitView) {
subgrids[item.id] = item.shipUnitView;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData");
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: subgrids[pureRowId],
colNames: ['Ship Type (Pallet / Carton)', 'Ship Unit (Pallet ID / Cone #)', 'Total Cartons'],
colModel: [
{ name: "shipUnitType", index: 'shipUnitType', width: 100, align: 'center'},
{ name: "reference", index: 'reference', width: 100, align: 'center'},
{ name: "totalOfCartons", index: 'totalOfCartons', width: 100, align: 'center'}
],
sortname: "shipUnitType",
sortorder: "desc",
height: "100%",
rowNum: 10,
autowidth: true,
autoencode: true,
jsonReader: {
root: "records",
records: "rows",
repeatitems: false,
id: "reference" },
gridview: true,
idPrefix: rowId + "_"
});
}
}).navGrid('#shipment_grid_pager', {edit: false, add: false, del: false, search: false, refresh: true});
});
This is my json data from the server:
{"page":1,
"records":[
{"id":2,"trackingNr":"1Z1484366620874728",
"shipUnitView":[{"reference":"65000943","shipUnitType":"CARTON","totalOfCartons":1},
{"reference":"65000942","shipUnitType":"CARTON","totalOfCartons":1}]},
{"id":4, "trackingNr":"1Z1484366620874746"
"shipUnitView":[{"reference":"65000940","shipUnitType":"CARTON","totalOfCartons":1},
{"reference":"65000939","shipUnitType":"CARTON","totalOfCartons":1}]},
{"id":3, "trackingNr":"1Z1484366620874764"
"shipUnitView":[{"reference":"65000938","shipUnitType":"CARTON","totalOfCartons":1},
{"reference":"65000937","shipUnitType":"CARTON","totalOfCartons":1}]}
],
"recordsTotal":3,"rows":10,"sidx":null,"sord":"asc","total":1,"trackingNr":null,"truckId":"174225","truckShipmentComponent":{}}
First of all there are small errors in the JSON data which you posted. It contains no commas after "trackingNr":"1Z1484366620874746" and "trackingNr":"1Z1484366620874764". I hope that it's only cut&paste error during preparing the data for the question. In any way it would be more safe to include loadError callback (see the answer) in case of loading errors.
Your main error seems to me are inside of beforeProcessing callback. The data parameter of the callback contains the server response. The array of items you have inside of data.records, but you use var rows = data.rows, ... instead. The line should be fixed to var rows = data.records, ....
One asked you in the comment to prepare JSFiddle demo which demonstrates the problem and you had problems to prepare it because of usage datatype: "json". On the other side JSFiddle do provides you possibility to implement demos in the case. One can use Echo service. In case of jqGrid one needs just use mtype: "POST" and url: "/echo/json/". To inform echo service which data you want to have one need just send JSON encoded data in json parameter. So the fill looks like
// the data which we want to receive back
var serverResponse = {
"page":1,
...
};
$("#gridId").jqGrid({
url: "/echo/json/", // use JSFiddle echo service
postData: {
json: JSON.stringify(serverResponse) // needed for JSFiddle echo service
},
datatype: "json",
mtype: "POST", // needed for JSFiddle echo service
...
});
The working JSFiddle demo you can find here: http://jsfiddle.net/OlegKi/ntfw57zm/. I makes some small additional optimization of your code.
I hope the example could help other people to post his questions with JSFiddle demos.
I'm having troubles reading this kind JSON from a server that i can't access, so i can't manipulate the JSON:
{
"API_ICDFactory": {
"API_getDataSample": {
"key_0": {
"dateTransaction": "1379454296",
"dateBilling": "1387320296",
"units": "181",
"priceUnit": "25.12",
"amount": "4546.72",
"company": "Juan Vivas Taller",
"productRef": "CAR",
"productDesc": "Detergente especial antiestático"
},
"key_1": {
"dateTransaction": "1377421074",
"dateBilling": "1385373474",
"units": "137",
"priceUnit": "8.99",
"amount": "1231.63",
"company": "Autos Caceres 2000",
"productRef": "BRICAR",
"productDesc": "Cera hidrofugante para túneles de lavado"
},
"status": "success"
}
}
}
I don't have exactly the idea of how to get the elements from this Json. If anyone could help me to do it.
I'm trying to manipulate this piece of code from th jqGrid documentation but i can't get any result.
jQuery(document).ready(function(){
jQuery("#grid").jqGrid({
url: "url...",
datatype: "json",
mtype: "GET",
colNames: ['Fecha Trans','Fecha Pago', 'Cliente'],
colModel: [
{name:'dateTransaction',index:'dateTransaction', width:100,editable:true},
{name:'dateBilling',index:'dateBilling', width:100,editable:true},
{name:'company',index:'company', width:100,editable:true}
],
jsonReader: {
repeatitems:false
},
rowNum:10,
rowList:[10,20,30],
pager: jQuery('#pager'),
sortname: 'name',
viewrecords: true,
sortorder: 'asc',
caption:'Title',
editurl:'url...'
}).navGrid('#pager');
});
If anyone could show me the correct syntax for this JSON i could do the rest.
Thanks!
You have to convert the JSON data returned from the server to array of items which can be read by jqGrid. Additionally I'd recommend you to use loadonce: true option so that you can use local paging, sorting and filtering/searing inside of jqGrid.
The conversion of input data you can do for example by defining root part of jsonReader as function. Alternatively you can use beforeProcessing callback to change server response. For example you can use the following jsonReader
jsonReader: {
root: function (obj) {
var input = obj.API_ICDFactory.API_getDataSample, p, res = [], item;
for (p in input) {
item = input[p];
if (input.hasOwnProperty(p) && typeof item === "object") {
item.id = p;
res.push(item);
}
}
return res;
},
repeatitems: false
}
The demo demonstrate my suggestion. It displays
The full code which I used you can find below:
$(function () {
"use strict";
var intTemplate = { width: 100, formatter: "integer", sorttype: "integer", align: "right" };
$("#grid").jqGrid({
url: "victorgb6.json",
datatype: "json",
colNames: ["Fecha Trans", "Fecha Pago", "Cliente"],
colModel: [
{ name: "dateTransaction", template: intTemplate },
{ name: "dateBilling", template: intTemplate },
{ name: "company" }
],
cmTemplate: {width: 250, editable: true},
gridview: true,
height: "auto",
autoencode: true,
loadonce: true,
jsonReader: {
root: function (obj) {
var input = obj.API_ICDFactory.API_getDataSample, p, res = [], item;
for (p in input) {
item = input[p];
if (input.hasOwnProperty(p) && typeof item === "object") {
item.id = p;
res.push(item);
}
}
return res;
},
repeatitems: false
},
rowNum: 10,
rowList: [10, 20, 30],
pager: "#pager",
viewrecords: true,
caption: "Title",
editurl: "myEditUrl"
}).jqGrid("navGrid", "#pager");
});
I'm trying to populate a JqGrid inside the success function of an Ajax call. My ajax call is passing a date parameter to the function which will filter the results. My grid loads, but no data is displayed and it says Loading... above my grids caption. I'm using a drop down to filter results based on date. My json data has been verified to be valid.
$(document).ready(function () {
$("[name='DDLItems']").change(function () {
var selection = $(this).val();
var dataToSend = {
//holds selected value
idDate: selection
};
$.ajax({
type: "POST",
url: "Invoice/Filter",
data: dataToSend,
success: function (dataJson) {
// alert(JSON.stringify(dataJson));
$("#grid").jqGrid({ //set your grid id
data: dataJson, //insert data from the data object we created above
datatype: json,
mtype: 'GET',
contentType: "application/json; charset=utf-8",
width: 500, //specify width; optional
colNames: ['Invoice_Numbers', 'Amt_Totals','f', 'ff', 't'], //define column names
colModel: [
{ name: 'Invoice_Number', index: 'Invoice_Number', key: true, width: 50 },
{ name: 'Amt_Total', index: 'Amt_Total', width: 50 },
{ name: 'Amt_Due', index: 'Amt_Due', width: 50 },
{ name: 'Amt_Paid', index: 'Amt_Paid', width: 50 },
{ name: 'Due_Date', index: 'Due_Date', width: 50 },
], //define column models
pager: jQuery('#pager'), //set your pager div id
sortname: 'Invoice_Number', //the column according to which data is to be sorted; optional
viewrecords: false, //if true, displays the total number of records, etc. as: "View X to Y out of Z” optional
sortorder: "asc", //sort order; optional
caption: "jqGrid Example", //title of grid
});
},
-- controller
[HttpPost] // Selected DDL value
public JsonResult Filter(int idDate)
{
switch (idDate)
// switch statement goes here
var dataJson = new UserBAL().GetInvoice(date);
return Json(new { agent = dataJson}, JsonRequestBehavior.AllowGet);
Here's the answer if anyone else comes across this. This is what I ended up doing, the rows are getting filtered passed on the date parameter I'm passing to the URL of the function. Having the Grid populate inside the Ajax call also seemed like it was a problem so I had to take it out.
public JsonResult JqGrid(int idDate)
{
switch (idDate)
#region switch date
--Switch Statement--
#endregion
var invoices = new UserBAL().GetInvoice(date);
return Json(invoices, JsonRequestBehavior.AllowGet);
}
[HttpPost] // pretty much does nothing, used as a middle man for ajax call
public JsonResult JqGridz(int idDate)
{
switch (idDate)
#region switch date
--Switch Statement--
#endregion
var invoices = new UserBAL().GetInvoice(date);
return Json(invoices, JsonRequestBehavior.AllowGet);
}
Yes these two functions seem very redundant and they are. I don't know why my post wouldn't update data, but I needed to reload the grid each time and when I did that it would call the first function. So yea the post jqGridz is kinda of just a middle man.
Here's the jquery code I used
var dropdown
var Url = '/Invoice/JqGrid/?idDate=0'
$(document).ready(function () {
$("#jqgrid").jqGrid({
url: Url,
datatype: 'json',
mtype: 'GET', //insert data from the data object we created above
width: 500,
colNames: ['ID','Invoice #', 'Total Amount', 'Amount Due', 'Amount Paid', 'Due Date'], //define column names
colModel: [
{ name: 'InvoiceID', index: 'Invoice_Number', key: true, hidden: true, width: 50, align: 'left' },
{ name: 'Invoice_Number', index: 'Invoice_Number', width: 50, align: 'left'},
{ name: 'Amt_Total', index: 'Amt_Total', width: 50, align: 'left' },
{ name: 'Amt_Due', index: 'Amt_Due', width: 50, align: 'left' },
{ name: 'Amt_Paid', index: 'Amt_Paid', width: 50, align: 'left' },
{ name: 'Due_Date', index: 'Due_Date', formatter: "date", formatoptions: { "srcformat": "Y-m-d", newformat: "m/d/Y" }, width: 50, align: 'left' },
],
pager: jQuery('#pager'),
sortname: 'Invoice_Number',
viewrecords: false,
editable: true,
sortorder: "asc",
caption: "Invoices",
});
$("[name='DDLItems']").change(function () {
var selection = $(this).val();
dropdown = {
//holds selected value
idDate: selection
};
$.ajax({
type: "POST",
url: "Invoice/JqGridz",
data: dropdown,
async: false,
cache: false,
success: function (data) {
$("#jqgrid").setGridParam({ url: Url + selection})
$("#jqgrid").trigger('reloadGrid');
}
})
})
});
Are you actually passing a value to your controller? I see you have data: dataToSend which doesn't match to your controllers idDate.
Is there a reason you are trying to setup your grid this way? Do you not want to deal with paging, or I'm not even sure if your setup would handle rebuild a grid when a user picks the date for a 2nd time.
My personal suggestion would be that you:
setup your grid separately, hidden if you don't want it visible on page load
set it's datatype to local so the grid doesn't load on page load
on the change event:
show the grid
change the postdata parameter the grid has
set the url of the controller/action which will feed the data back to the grid
trigger a grid reload
I have set up jqGrid to display my data, even though data is coming from the server, data is not displayed in the grid.
This is the server response.
Here is the JavaScript.
<table id="Grid1" class="scroll"></table>
<div id="pager" class="scroll" style="text-align:center;">
<script>
$(document).ready(function () {
jQuery("#Grid1").jqGrid({
url: 'api/matchingservicewebapi/getuser',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'Account', 'Ref', 'BDate'],
colModel: [
{ name: 'Id', index: 'Id', width: 200 },
{ name: 'Account', index: 'Account', width: 300 },
{ name: 'Ref', index: 'Ref', width: 300 },
{ name: 'BDate', index: 'BDate', width: 300 }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pager',
sortname: 'Id',
viewrecoreds: true,
sortorder: "desc",
imgpath: 'Themes/images'
}).navGrid(pager, { edit: true, add: true, del: true, refresh: true, search: true });
});
Below is the JSON format of data
{"Data":{"rows":[{"id":200.0,"cell":["100","AMX.Data.Account","200","1/10/2010 12:00:00 AM"]},{"id":14726632.0,"cell":["600146","AMX.Data.Account","14726632","1/8/2010 12:00:00 AM"]},{"id":6633000.0,"cell":["668152","AMX.Data.Account","6633000","1/8/2010 12:00:00 AM"]},{"id":2053178.0,"cell":["600146","AMX.Data.Account","2053178","1/8/2010 12:00:00 AM"]},{"id":753550.0,"cell":["668152","AMX.Data.Account","753550","1/8/2010 12:00:00 AM"]},{"id":121774.0,"cell":["600146","AMX.Data.Account","121774","1/8/2010 12:00:00 AM"]},{"id":37900.0,"cell":["600146","AMX.Data.Account","37900","1/8/2010 12:00:00 AM"]},{"id":6569.0,"cell":["668152","AMX.Data.Account","6569","1/8/2010 12:00:00 AM"]},{"id":-1124870617.0,"cell":["668152","AMX.Data.Account","-1124870617","1/8/2010 12:00:00 AM"]},{"id":-813658270.0,"cell":["668152","AMX.Data.Account","-813658270","1/8/2010 12:00:00 AM"]}]},"JsonRequestBehavior":0}
But data is not getting loaded. What am I doing wrong?
As noted in the comments by Mostafa & txominpelu. Try formatting your JSON result as follows
{"total":1123,
"page":1,
"records":1123,
"rows":[{"id":1174,
"cell":["1174","4","",...]
}]
}
and on the server side
public ActionResult GridData(int page, int rows, string searchField = "",
string searchString = "", string searchOper = "", string sidx = "MY_ID",
string sord = "desc")
{
//...
var jsonData = new {
total = totalPages,
page,
records = totalRecords,
rows = (from item in items.ToList()
select new {
id = item.MY_ID,
cell = new[] {
#region items
ToSafeString(item.MY_ID),
ToSafeString(item.ShiftID),
//...
#endregion
}
}).ToArray()
};
}