Jqgrid inline edit for selectList hits server for each row - jqgrid

i have set ,
editoptions: { aysnc: true, dataUrl: 'ControllerName/MethodName?__SessionKey=' + sessionkey + "&Id=" + Id, buildSelect: buildSelectFromJson, style: "width: calc(100% - 65px);",
dataEvents: [
{
type: 'change',
fn: function (e) {}
}
]
}
in which buildSelectFromJson returns select list in html.
Now dataurl hits server for each row but my select list is same for all rows. so how can i restrict to a single hit and then use that select list for all other rows?

I can suggest you two alternatives:
the server code (responsible for the URL ControllerName/MethodName) can place HTTP caching header. For example Cache-Control: private, max-age=(time in seconds). It will force getting the data during specified time interval from the local web browser cache.
You can make Ajax request to ControllerName/MethodName separately and set editoptions.value based on the response instead of usage editoptions.dataUrl (only if dataUrl is undefined the value will be used). See the answer for the code example of the possible implementation. By the way you can combine the call to ControllerName/MethodName with the main call for filling the grid. See the answer and this one.
By the way the property aysnc: true which you use in editoptions is unknown and it will be ignored.

Related

JqGrid Performance - setRowData lags

setRowData takes almost 5 seconds when the grid has 300 rows, 30 cols, and 4 frozen cols.
$("#tbl").jqGrid({
gridview: true,
url: '../controller/GetData',
datatype: "json",
rowNum: pageSize,
viewrecords: true,
loadtext: '',
loadui: 'disable',
rowList: [1000, 2000, 3000],
width: $(window).width() - LeftMargin,
shrinkToFit: false,
pager: '#dvPager',
pagerpos: 'left',
colNames: GetColNames(selectedViewName, viewCols),
colModel: GetColModel(selectedViewName, viewCols),
cmTemplate: {
title: false
},
recordtext: "Displaying {0} - {1} of {2}",
rowattr: function (rowData) {
},
//onCellSelect: function (rowid, iCol, cellcontent, e) {
// e.stopPropagation();
// proto.editcell(rowid, iCol, cellcontent, e);
//},
loadComplete: function (data) {..},
onPaging: function (data) {..},
serializeGridData: function (postData) {..}
});
Can you please guide me with the performance tuning tips?
In GetColModel we are binding columns as follows -
'Discount': {
name: 'Discount', index: 'Discount', width: colModelWidthDict['Discount'], title: false, sortable: false, resizable: colResizable, hidden: !bReadCalculationSellInfo,
formatter: function (cellValue, option, rowObject) {
if (rowObject.level == 0 || (rowObject.Flag == 0 && (rowObject.Discountable && rowObject.Discountable.toLowerCase() == 'no')))
return '';
else {
if (!proto.IsReadOnly(rowObject) && ((rowObject.Flag == 0 && (rowObject.Discountable && rowObject.Discountable.toLowerCase() == 'yes')) || rowObject.Flag > 0))
return proto.GetControls("Discount", option.rowId, "Numeric", rowObject.Discount, 6, 90)
else
return '<span class="amt">' + cellValue + '</span>';
}
},
unformat: function (cellValue, option) {
return cellValue;
},
cellattr: function (rowId, val, rowObject, cm, rdata) {
if (parseInt(rowObject.PPPChngDisc) == 1)
return ' style="color:red"';
}
}
//code for colModel - 1 column above
In general you should prefer to modify only small number of rows. If you modify one row then the web browser have to recalculate position of all other rows (500 rows) of the grid. In the case modifying 300 rows means 300*500 operations for the web browser.
If you fill the whole grid and you use gridview: true option then jqGrid places at the beginning all the data for the grid body in array of strings. After preparing of all information in string format jqGrid place the whole body of the grid as one operation. It's just one assigning innerHTML property of tbody. Thus it's more effective to reload the whole grid as to make modification of many rows of the grid in the loop using setRowData.
So I would recommend you to reload the grid in your case.
Moreover you should consider to reduce the number of rows in the page of grid. If you use rowNum: 500 you just reduce the performance of your page tin many times without any advantage for the user. The user can see about 20 rows of the data only. Only if the user scrolls he/she is able to see another information. In the same way the user could click next page button. Holding 500 rows force web browser make a lot of unneeded work. Modifying of the first row from 500 the web browser have to recalculate position of all 500 rows. Even if the user move the mouse over a row the web browser change the class of the hovering row and it have to recalculate position of all other from 500 rows event the rows are not visible.
One more remark. The implementation of frozen columns in jqGrid 4.6 is slow. Starting with the end of 2014 and publishing 4.7.1 with changing Lisanse and making jqGrid commercial I develop free jqGrid as fork based on jqGrid 4.7 (see the readme for more details). I implemented a lot of changes and new features in the fork. The recent changes includes many improvement of frozen columns feature. If you loads free jqGrid or just try it directly from GitHub by including the corresponding URLs (see the wiki) you will see that the performance of frozen columns is dramatically improved. Additionally frozen columns supports now row and cell editing in all editing modes. I plan to publish free jqGrid 4.9 soon. So I recommend you to try it.
UPDATED: You posted the code, which you use in comments below. I see the main problem in the implementation of Process function which will be called on change in the <input> fields on the grid. I recommend you to try something like this one:
function Process(contrl) {
var $cntrl = $(contrl),
$td = $cntrl.closest("tr.jqgrow>td"),
$tr = $td.parent(),
rowId = $tr.attr("id"),
newValue = $cntrl.val(),
$grid = $("#list"),
p = $grid[0].p,
colModel = p.colModel,
columnName = colModel[$td[0].cellIndex].name, // name of column of edited cell
localRowData = $grid.jqGrid("getLocalRow", rowId),
iColTotal = p.iColByName.total;
// modify local data
localRowData[columnName] = newValue;
localRowData.total = parseInt(localRowData.quantity) * parseFloat(localRowData.unit);
// modify the cell in the cell (in DOM)
//$grid.jqGrid("setCell", rowId, "total", localRowData.total);
$($tr[0].cells[iColTotal]).text(localRowData.total);
return false;
}
One can event improve the code and not use setCell at all. It's important to understand that local grid hold the data in the form of JavaScript object. The access to the data is very quickly. You can modify the data without any side effects existing with DOM elements. In the above code I use only relative search inside of the DOM of the row using closest and parent. It works very quickly. I recommend to save $("#list") in the variable outside of the Process (move var $grid = $("#list") in the outer function) and just use $grid variable. It will make access to the DOM of page very quickly. The line localRowData = $grid.jqGrid("getLocalRow", rowId) get the reference to internal JavaScript data object which represent the internal data of the row. By modifying the data by localRowData[columnName] = newValue; or localRowData.total = ... we make the half of job. One need only to change the value in the DOM on the cell Total. I used iColByName which exist in the latest sources of free jqGrid on GitHub. It get just the column index in colModel by column name. One can find the same information alternatively if one use more old jqGrid. The line $($tr[0].cells[iColTotal]).text(localRowData.total); shows how to assign manually the data in the cell. It's the most quick way to do this, but one assign the data without the usage formatter. For more common case (for example in case of frozen "total" column) one can use the commented row above: $grid.jqGrid("setCell", rowId, "total", localRowData.total);.

stop reloading dropdowns after add

Here is the code of my dropdown.
{
name: 'ClassId', index: 'ClassId', align: 'center',editable: true, edittype: 'select',
editoptions: {
dataUrl:'#Url.Action("GetAllClasses", "Class", new { Area = "Curriculums"})',
buildSelect: function (data) {
var response, s = '<select>', i;
response = jQuery.parseJSON(data);
//s += '<option value="0">--Select Class--</option>';
if (response && response.length) {
$.each(response, function (i) {
s += '<option value="' + this.Id + '">' + this.ClassName + '</option>';
});
}
return s + '</select>';
}
}
},
I am using form edit.I am reloading grid after insert.But the problem is after inserting data when I try to add another one my dropdowns are getting refreashed.I want that the dropdown selected value will be previously selected value.I don't want to change dropdown selected value on the second add.
The most simple way to prevent reloading of data from dataUrl could be setting Cache-Control HTTP header in the server response. Setting of Cache-Control: max-age=60 in the server response for example will prevent reloading of data from the server during 60 sec. In case of ASP.NET MVC you can use CacheControl attribute for example (see Duration and Location properties).
One more alternative would be dynamical setting editoptions.value instead of usage editoptions.dataUrl. For example one can include the information needed for building editoptions.value as an extension of the standard response of the server for filling the grid. One can use beforeProcessing to process the part of the data. You will find the corresponding examples in the following cold answers: this one, this one, this one, this one, this one and other. The answer describes in short one of the the possible scenario to create full dynamic grid.

Proper way to page jqGrid

I need to display a number of "dynamic" grids using jqGrid. By dynamic I mean that both definition and data of the grid are retrieved from a database. There are many grids on the page, so I am trying to minimize the number of server trips, and there is a lot of data, so server-side paging is a must.
My workflow is
On initialization of each grid, retrieve grid definition and first
page of data in one server call.
If a user sorts/pages, then retrieve a page of data from the server
Because I want to retrieve the grid definition and first page of data in one call, I cannot use datatype: 'json', url: '###' approach; instead I do:
grid.jqGrid({
mtype: 'post',
...
datatype: function (postdata) {
if (!init.data) {
var request = {
screenId: settings.screenId,
pageNumber: postdata.page,
pageSize: postdata.rows,
sortColumn: postdata.sidx,
sortDirection: postdata.sortd,
date: settings.date
};
site.callWs("/MyService", request, function (pageResponse) {
//WHAT TO CALL HERE TO SET A PAGE OF DATA?
});
} else {
//WHAT TO CALL HERE TO SET A PAGE OF DATA?
init.data = null;
}
}
});
My data object (pageResponse or init.data) looks like this
I am not sure what method to call on jqGrid once a page of data is returned. I considered addJSONData, but it seems so inefficient to convert JSON back to string, then use EVAL(). Also, considered addRowData or setting the data property, but I am confused how to instruct jqGrid that I am doing server-side paging -- if I set the data property to one page of records, what do I need to do to tell jqGrid that there is a total of 50 records and this is page 1 out of 10.
Thanks for your help.
It was a user error (mine :). I had some show/hide logic in loadComplete of jqGrid, but this event does not fire when addJSONData is called.
addJSONData works just fine when provided with a properly-structured JavaScript object.

jqgrid - saveRow url throwing an exception

In inline editing mode, clicking on "Save" is throwing an error.
var rowSave = function(id){
jQuery("#myjqgrid").jqGrid('saveRow',id,{
"succesfunc": function(response) {
return true;
},
"url": myjqgrid.json
"mtype": "GET"
});
}
Is it because the url is set to json?
Basically, I get JSON response when the grid is loaded the first time. After I edit the row in inline editing mode, the edited data should be sent to the server. When the data is saved on the server, it should return the updated JSON and the grid row data should be updated with the updated JSON response.
Looking at this doc page:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing#saverow
in the section for saveRow it says:
url: if defined, this parameter replaces the editurl parameter from the options array. If set to 'clientArray', the data is not posted to the server but rather is saved only to the grid (presumably for later manual saving).
and a bit below:
Except when url (or editurl) is 'clientArray', when this method is called, the data from the particular row is POSTED to the server in format name: value, where the name is a name from colModel and the value is the new value.
so it seems you need to supply the server URL that will accept data here. In some of the examples on the same page you can see something like this:
...
editurl: "server.php",
...

jqGrid 4.2 Custom search with non-grid fields

I'm using jqGrid 4.2 with the filterToolbar, which works great. I'd like to add some type of custom search to query (server-side) fields that are not part of the colModel.
Prior to 4.0 I would have used filterGrid along the lines of this:
$('#keyword').jqGrid('filterGrid', '#ticket-grid',
{
gridModel: false,
filterModel: [
{ label: 'Keyword', name: 'keyword', stype: 'text'},
{ label: 'Inclued Closed?',name : 'includeClosed', stype: 'checkbox'}
]
});
I understand that this is no longer supported, and an stype: 'checkbox' doesn't work anyway.
How do I do this with the new search module/mechanism?
If I understand you correct you have already on the page, for example above the grid, some controls (text input, selects, chechboxes) which allow the user to define additional criteria of the results which the user want see in the grid. In the case you can use postData with methods (functions) in the way described in the old answer.
If any kind of grid refreshing: request to filter the data from the searching toolbar, changing of the page or the page size, changing of sorting and so on will always follow to the Ajax request to the server. In the case the properties from postData option of jqGrid will be added like other standard parameters (sidx, sord, page, ...). If one from the properties of the postData is defined as function (if a method of postData) then the function will be called to construct the parameter which will be sent to the server. So the current information from you custom searching controls (text input, selects, chechboxes) will be send to the server. In the way you need only use the parameters on the backend to filter the results.
So you have to define fields yourself. For example the text input with id="keyword-input" and checkbos with id="includeClosed" and then use postData in about the following form:
$('#keyword').jqGrid(
// ... other jqGrid options
postData: {
keyword: function () { return $('#keyword-input').val(); },
includeClosed: function () { return $('#includeClosed')is(':checked'); },
}
});

Resources