jqGrid: function $("#gridView").jqGrid("getGridParam", "data") return null? - jqgrid

I had a problem with jqGrid
When i use:
$("#gridView").jqGrid({
url:"grid.php",
colModel:[
{ name: 'id', index:'id'},
],
datatype: "json",
mtype:"post",
height:350,
rownumbers:true,
treeGrid: true,
treeGridModel : 'adjacency',
ExpandColumn : 'id',
ExpandColClick: true
....
$("#gridView").jqGrid("getGridParam", "data") return array
$("#gridView").jqGrid({
url:"grid.php",
colModel:[
{ name: 'id', index:'id'},
],
datatype: "json",
mtype:"post",
pager:"#pager",
rowNum:50,
rowList:[10,50,100,500,1000],
viewrecords:true,
height:350,
rownumbers:true,
....
$("#gridView").jqGrid("getGridParam", "data") return null ??
I've read article here JQGrid getGridParam not returning ID of data item
But I cannot set loadonce:true because of my dynamic data for each click

You don't need to use loadonce: true in case of treeGrid: true. jqGrid fills internal parameters data and _index for treegrid automatically (see the part of the code).
I suppose that you get null as the value of data parameter because you try to access data before the data will be loaded from the server. Try to use $(this).jqGrid("getGridParam", "data") inside of loadComplete callback. The callback will be called after filling of data.

Related

How to access id of onSelectRow in delOptions action method in jqGrid

//Hidden Input element
//my grid details:
$("#jqGrid").jqGrid({
url: '#Url.Action("EditedEventData", "Calendar" ,new{ })' + '?CountryId=' + #countryid + '&CityId=' + #cityid ,
async: true,
datatype: "json",
colModel: [
//label: "Edit Actions",
name: "",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
edit: true,
add: true,
del: true,
editOptions: {},
addOptions: {},
delOptions: {
url:'#Url.Action("RemoveEvent", "Calendar")'+ '?HolidayId='+document.getElementById('hdnEventId').value ,
//mtype: 'POST',
}// **here it is showing hdnEventId value empty**
}
}
],
onSelectRow : function(id){
console.log('inside onSelectRow');
alert(id);
document.getElementById('hdnEventId').value=id;
alert(document.getElementById('hdnEventId').value);
},
sortname: 'EventDate',
loadonce: true,
width: 750,
height: 200,
rowNum: 150,
pager: "#jqGridPager"
});
I am unable to access id of onSelectRow in delOptions action method.
So thought of taking a hidden html element and store the value but it is showing empty.
Thanks in advance
When a delete is performed the id is automatically send to the server. The parameter which is obtained via post is named id.
If you additionally want to fill a id on deleting a rows you can use some events to fill the field you want. These are described here. In the same documentation see the chapter What is posted to the server .
To fill the id in another field when a row is deleted I think the good choice is to use either serializeDelData or afterSubmit events - see the events on the same link.
When use these events the parameter postdata contain the id. By example in serializeDelData (set this in delOptions) this can look like
serializeDelData : function( postdata ) {
var id = postdata.id;
document.getElementById('hdnEventId').value=id;
return postdata;
}
Remember both events should return some params

Mapping data to JQGrid with Ajax call

I'm just trying to display a very simple JQGrid with data from an ajax call to a controller. All I'm seeing is the grid headers, no data. Can someone please help me figure out what I'm doing wrong? Thanks in advance!
Here's the Ajax call and JQGrid setup..
$("#grid").jqGrid({
url: '#Url.Action("GetLoanReport", "Report")',
datatype: "json",
height: "auto",
colNames: ['Name', 'Random Stuff'],
colModel: [
{ name: 'Name', index: 'Name', width: 150, sortable: true },
{ name: 'RandomStuff', index: 'RandomStuff', width: 500, sortable: false }
],
jsonReader: {
repeatitems: true,
root: 'rowdata',
page: 'currpage',
total: 'totalpages',
records: 'totalrecords'
},
rowNum: 10,
rowList: [5, 10, 30],
rownumbers: false,
gridview: true,
loadonce: true,
pager: "#page",
caption: "Flat Data Example"
});
Here's the controller code...
Function GetLoanReport() As JsonResult
ViewData("Ribbon") = "partials/_statsRibbon"
Dim response As New Response
Dim model As New ReportModel
model.Name = "Mark"
model.RandomStuff = "Highfield"
response.currpage = 1
response.totalpages = 1
response.totalrecords = 1
response.rowdata = model
Return Json(response, JsonRequestBehavior.AllowGet)
End Function
The main problem: rowdata should be array of items (array of objects) instead of one object only with Name and RandomStuff properties.
Additionally you should decide whether you implement server side paging of data or you want to return all the data from GetLoanReport at once and jqGrid should make local paging, sorting and filtering/sorting the data? In the case you should use loadonce: true option. Additionally it's important to choose the fork of jqGrid, which you use: free jqGrid, commercial Guriddo jqGrid JS or an old jqGrid in version <=4.7. I develop free jqGrid fork, which I can recommend you. If you use it, then I would recommend you to add forceClientSorting: true option additionally to loadonce: true. It will allows you to use sortname and sortorder options to sort the data returned from the server before it will be displayed.

SetLabel method of jqGrid along with setGroupHeaders

I am trying to use setlabel method of jqGrid along with setGroupHeaders. It does not work. But when I remove this setGroupHeaders, setLabel method works and I am able to change my column headers dynamically. Is there anyway to use both of the methods together?
Adding the code fragment
$("#aGrid").jqGrid({
shrinkToFit: false,
autowidth: true,
height: 305,
colNames: ['Parameter','T0','T1','T2','T3'],
colModel: [
{name:"paramName",index:"paramName",width:115,sortable:false,frozen:true},
{name:"t0",index:"t0",cellattr:myFormatter,hidden:false},
{name:"t1",index:"t1",cellattr:myFormatter,hidden:false},
{name:"t2",index:"t2",cellattr:myFormatter,hidden:false},
{name:"t3",index:"t3",cellattr:myFormatter,hidden:false}
],
viewrecords: true,
gridview: true,
sortable: false,
caption: "A Grid"
});
$("#aGrid").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders: [
{startColumnName:'t0',
numberOfColumns:8,
titleText:'10.152.141.142'}]
});
$.ajax({
type : "get",
url : url,
dataType: "json",
contentType: "application/json",
success : function(responseText){
for(var i=0;i<=responseText.length;i++)
{
if(i === 0){
var newColHeaders = responseText[i];
$("#aGrid").jqGrid('setLabel', "t0",newColHeaders['t0']);
$("#aGrid").jqGrid('setLabel', "t1",newColHeaders['t1']);
$("#aGrid").jqGrid('setLabel', "t2",newColHeaders['t2']);
$("#aGrid").jqGrid('setLabel', 't3',newColHeaders['t3']);
}else{
$("#aGrid").jqGrid('addRowData',i+1,responseText[i]);
}
}
},
error: function(xhRequest, ErrorText, thrownError){
}
});
If I use the same code after removing setGroupHeaders call in above code, column headers change works as expected.
This issue is because of your group header.
When you want to change the header, first destroy the group header and then call the setLabel and again reconstruct the group Header.
$("#aGrid").jqGrid('destroyGroupHeader');
//Now change the Label of header
$("#aGrid").jqGrid('setLabel', "to","ABC"); //colModel name value
constructGroupHeader();
Construct group Header should be like this
function constructGroupHeader()
{
jQuery("#aGrid").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders: [
{startColumnName:'t0',
numberOfColumns:8,
titleText:'10.152.141.142'}]
});
}
Hope this helps.

How to load data (json) in jqgrid via ajax?

i need to populate jqgrid after ajax's call.
I have a function (in java servelet) that returns this json format:
[{"citta":"XXXX","via":"XXX","telefono":"1111-11111","provincia":"XX","clienteDesc":"Prova","clienteCode":"XXXXX"}]
and i use this code for the jqgrid:
$("#clienti-navgrid").jqGrid( {
//data: c
//datatype: "local"
datatype: "json",
url: '/project/loadnotespese.do',
colNames:['Codice Cliente','Descrizone Cliente','Via','Città','Provincia','Telefono'],
colModel:[
{name:'clienteCode', index:'clienteCode', width:'10', sortable:false},
{name:'clienteDesc', index:'clienteDesc', width:'20', sortable:false},
{name:'via', index:'via', width:'30', sortable:false},
{name:'citta', index:'citta', width:'20', sortable:false},
{name:'provincia', index:'provincia', width:'10', sortable:false},
{name:'telefono', index:'telefono', width:'10', sortable:false}
],
rowNum:500,
autowidth:true,
height:'auto',
recordtext:"Ordini trovati {2}",
emptyrecords:"Nessun risultato",
viewrecords: true,
caption: 'Tabella Clienti',
localReader : {
//
repeatitems: false,
}
});//jqGrid
if i put
var c = [{"citta":"XXXX","via":"XXX","telefono":"1111-11111","provincia":"XX","clienteDesc":"Prova","clienteCode":"XXXXX"}]
and
data: c, datatype: "local",
works, but if i'll get from url: '/project/loadnotespese.do', it dosen't work.
Any help?
If you use datatype: "local" the option localReader will be used. By the way the value repeatitems: false is default value for localReader (see the documentation). So in case of usage datatype: "local" you can event remove the current option localReader: { repeatitems: false } from the list of the options.
On the other side if you use datatype: "json" another option jsonReader will be used. The default value of repeatitems property of jsonReader is repeatitems: false (see the documentation). So you have to add
jsonReader: { repeatitems: false }
in the case to the list of jqGrid options. After that the grid should be successfully filled.
One other important think which is important to know is specifying additional of id property in every item of the row of data. The id value must be unique over the whole page and it will be used as the value of id attributes of the rows (<tr>) elements of the grid body. If some other property of the row items can be used as the unique id you can either include additional setting in jsonReader or add key: true property in the corresponding definition of the column in colModel. For example if clienteCode can be interpreted as the rowid you can use
jsonReader: { repeatitems: false, id: "clienteCode" }
UPDATED: You should use additionally
root: function (obj) { return obj; }
inside of jsonReader (see here). So the final jsonReader should be
jsonReader: {
repeatitems: false,
id: "clienteCode",
root: function (obj) {
return obj;
}
}

Loading json data into jqgrid using setGridParam

I'm having some issues setting the url of the jqgrid using setGridParam.
I receive the message: "f is undefined".
My setup:
$("#prices").jqGrid({
colModel: [
...
],
pager: jQuery('#pricePager'),
ajaxGridOptions: { contentType: "application/json" },
mtype: 'POST',
loadonce: true,
rowTotal: 100,
rowNum: -1,
viewrecords: true,
caption: "Prices",
height: 300,
pgbuttons: false,
multiselect: true,
afterInsertRow: function (rowid, rowdata, rowelem) {
// ...
},
beforeSelectRow: function (rowid, e) {
// ...
},
onSelectRow: function (rowid, status) {
// ...
}
});
Getting the data:
$("#prices").setGridParam({ datatype: 'json', page: 1, url: '#Url.Action("GridDataPrices")', postData: JSON.stringify(selections) });
$("#prices").trigger('reloadGrid');
The Response is non encoded json:
{"total":1,"page":1,"records":100,"rows":[{"id":160602948,"StartDate":"\/Date(1311717600000)\/","Duration":7,"Price":1076.0000,"Code":"code"},{"id":160602950,...}]}
However, I get following message, using firebug:
"f is undefined"
I got this working first using addJSONData, but had to replace it because I want to preserve the local sorting.
Thanks in advance.
After you uploaded the code all will be clear. Your main errors are the follwings:
you should include datatype: 'local' in the jqGrid. Default value is 'xml'.
the JSON data have named properties so you have to use jsonReader: { repeatitems: false } (see the documentation for details)
you use "ArivalCodeWay" in colModel and "ArrivalCodeWay" in the JSON data. So you should fix the name of the corresponding jqGrid column
to decode the date from the "\/Date(1312840800000)\/" format you should include formatter:'date' in the corresponding column.
In the same way I find good to include formatter:'int', sorttype:'int' in the 'Duration' column and sorttype:'number', formatter:'number', formatoptions: { decimalPlaces:4, thousandsSeparator: "," } in the 'Price' column.
if you use JSON.stringify you should include json2.js to be sure that your code will work in all web browsers.
The modified demo (including some other minor changed) you can find here. If you click on "Click me" button the grid contain will be loaded.

Resources