Jqgrid Subgrid data fetching from server on expand only - jqgrid

I am using Jqgrid (version 5.2.0 ,paid). I am loading the main grid on a button click on the page(aspx page is with masterpage and update panel) and using code to re-instantiate grid and reload grid on button, datatype: local and data='' on grid creation.
I need to load the sub-grid data from server on each main grid row expand only(I will have a lot of data in main grid, loading the sub-grid also on button click is making it slow.)
How to load the subgrid data on row expand?
function createsamplegrid() {
jQuery("#grid").jqGrid({
url: '',
datatype: 'local',
colNames: ['Id', 'StoreName', 'Department'],
colModel: [
{ name: 'ID', index: 'ID', width: 20, stype: 'text' },
{ name: 'StoreName', index: 'StoreName', width: 150 },
{ name: 'Department', index: 'Department', width: 150 }
],
rowNum: 10,
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption: "List Employee Details",
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowId) {
var subgridTableId = subgridDivId + "_t",
localRowData = $(this).jqGrid("getLocalRow", rowId);
$("#" + subgridDivId).html("<table id='" + subgridTableId + "'></table>");
$("#" + subgridTableId).jqGrid({
datatype: 'local',
data: '',
colNames: ['ID', 'Employee Name'],
colModel: [
{ name: 'ID', index: 'ID', width: 70, align: "left", hidden: true },
{ name: 'EmployeeName', index: 'EmployeeName', stype: 'text', align: "left" }
],
jsonReader: {
root: 'gridModel',
repeatitems: false
},
idPrefix: rowId + "_"
});
}
});
}
function GetSampleData() {
$.ajax({
type: "POST",
url: 'Sample.aspx/GetSampleDetail',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (Result) {
var myjsongrid = $.parseJSON(Result.d);
SampleData = myjsongrid;
$('#grid').jqGrid('clearGridData');
$("#grid").jqGrid('setGridParam', { data: myjsongrid, datatype: 'local' }).trigger('reloadGrid');
},
error: function (jqXHR, exception) {
}
});
}
function ReinstantiateGrid() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
} // fires after the partial update of UpdatePanel
function EndRequest(sender, args) {//Calls the function again to load the grid after partial postback
createsamplegrid();
GetSampleData();
}
}

Related

Sometimes jqgrid getChangedCell not return checkbox changed

when I insert/update table data. i use getChangedCell function for making input data before call API. like this.
let inputData = _$myTable.getChangedCells('all');
$.ajax({
type: "POST",
url: "/api/services/InsertData",
dataType: "json",
data: inputData
})
Please check sample image.
First I check checkbox. after then click save button.
At this moment, generally _$myTable.getChangedCells('all') return the correct value.
But, sometimes _$myTable.getChangedCells('all') return []
Table options are :
_$myTable.jqGrid({
mtype: "GET",
datatype: "local",
autowidth: true,
shrinkToFit: false,
cellEdit: true,
colModel: [
{
name: "id",
key: true,
hidden: true
},
...
],
onSelectRow: function (id) {
if (id && id !== optionlastsel) {
_$myTable.jqGrid('restoreRow', optionlastsel);
_$myTable.jqGrid('editRow', id, true);
optionlastsel = id;
}
},
afterEditCell: function (rowid, cellname, value, iRow, iCol) {
var checkboxNameSet = _.pluck(_.where(_$myTable.jqGrid("getGridParam").colModel, { edittype: 'checkbox' }), 'name');
if (checkboxNameSet.includes(cellname)) {
$('#' + rowid + '').addClass("edited");
}
}
})
Checkbox options are:
{
label: 'IsActive',
name: "isActive",
editable: true,
edittype: 'checkbox',
editoptions: { value: "true:false" },
editrules: { required: true },
formatter: "checkbox",
formatoptions: { disabled: false },
align: "center"
}
In addition, all the time, the network was fine.
Are there any options I missed or mistake?
Thank you for reading.

Add check boxes in Jquery grid view

I have the following code in page which binds the data to j query grid.
Now i want to add one more column for check-boxes to the existing grid and when i select some check boxes and press some button .. i need to get the selected row values .
I have seen some tutorials for this they mentioned about some formatter .... but they are not clear
Please help me to achieve this.
Thanks in advance.
Code:
$(document).ready(function () {
$("#btn_GenerateEmpList").click(function () {
var firstClick = true;
if (!firstClick) {
$("#EmpTable").trigger("reloadGrid");
}
firstClick = false;
var empId= $("#txt_emp").val();
$.ajax({
type: "POST",
url: "PLBased.aspx/GetEmpNames",
data: JSON.stringify({ empId: empId}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
result = result.d;
jQuery("#EmpTable").jqGrid({
datatype: "local",
colNames: ['Emp Name'],
colModel: [
{ name: "EmpName", Index: "EmpName", width: 80 }
],
data: JSON.parse(result),
rowNum: 10,
rowList: [5, 10, 20],
pager: '#pager',
loadonce: false,
viewrecords: true,
sortorder: 'asc',
gridview: true,
autowidth: true,
sortname: 'EMPID',
height: 'auto',
altrows: true,
});
},
error: function (result) {
alert("There was some error ");
}
});
});
});
You can use customformatter to show checkbox in the column. For this, you can write the code as below in your jqGrid Code.
colNames: ['Id','Emp Name','Emp Checkbox'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'EmpName', Index: 'EmpName', width: 80 },
{ name: 'Empchk', Index: 'Empchk', width: 50, align: 'center', editable: true, edittype: "checkbox", editoptions: { value: "true:false" },
formatter: generateEmpCheckBox, formatoptions: { disabled: false } }
],
formatter function code as below,
function generateEmpCheckBox(cellvalue, options, rowObject) {
var checkedStr = "";
if (cellvalue == true) {
checkedStr = " checked=checked ";
}
return '<input type="checkbox" onchange="UpdateEmpcheckbox(' + rowObject.Id + ',this)" value="' + cellvalue + '" ' + checkedStr + '/>';
}
function UpdateEmpcheckbox(selectedId, chkBox) {
if ($(chkBox).prop("checked")) {
//you can write an ajax here, to update the server
//when the checkbox is checked
}
else if (!($(chkBox).prop("checked"))) {
//you can write an ajax here to update the server
//when the checkbox is unchecked
}
return false;
}
Set the option multiselect:true which will add column of checkboxes. Then add
$('#EmpTable').jqGrid('getGridParam', 'selarrrow')
will return an array of selected id's.

Change edittype on addparam and editparam in JqGrid inline Navigator

I have two dropdowns in jqgrid inline navigator. I want to enable both dropdown only for add mode,and only one dropdown for edit mode.
grid = $("#gridTable");
grid.jqGrid({
colModel: [
{ name: 'empId' , width: "250",editable:true,edittype: 'select',editoptions:{value: {"Emp1","Emp2"}}, formoptions:{ rowpos:1, label: "Emp Id", elmprefix:"(*)"},editrules:{required:true}},
{ name: 'Address' , width: "250",editable:true,edittype: 'select',editoptions:{value: {"Emp Add1","Emp Add2"}}, formoptions:{ rowpos:2, label: "Address", elmprefix:"(*)"},editrules:{required:true}}
],
pager: '#gridTablePager',
colNames:[ 'empId', 'Address'],
rowList:[10,20,50,100,200,500],
datatype: "jsonstring",
datastr: dataInDb,
jsonReader: { repeatitems: false },
viewrecords: true,
height: 300,
ignoreCase: true
});
What code I should add for this?
Could anyone help?
you can do something like this.
grid.jqGrid('inlineNav', "#" + paginator, {
addParams: {
addRowParams: {
url: baseUrl + 'Plantilla/InsertCaracteristicaPlantillaTemp',
mtype: "POST",
oneditfunc: function (rowid) {
InitModel(rowid, 'I');
}
},
editParams: {
url: baseUrl + 'Plantilla/UpdateCaracteristicaPlantillaTemp',
mtype: "POST",
oneditfunc: function (rowid) {
InitModel(rowid, 'U');
}
});
function InitModel(rowid, Operation){
if(Operation == "U")
$("#" + rowid + "_fielName").attr("disabled", true);
}
Now, with that function you can enable and disable fields when you want.

jqGrid Switch a field to dropdown from text

Ive got a jqGrid where i have a some columns and 1 of the columns is a dropdownlist(select) populated from database.
What i want is : When im not in editmode column with dropdowns just have to show text which have to be taken from query, and when im in edit mode it should show dropdown list.
exactly like here: http://www.trirand.com/blog/jqgrid/jqgrid.html go into row editing/input tipyes
here is the code for my grid:
<script type="text/javascript">
var lastsel;
$(document).ready(function () {
$.getJSON('#Url.Action("ConstructSelect")', function (data) {
setupGrid(data);
});
});
function setupGrid(data) {
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("GetStoreList")',
datatype: 'json',
mtype: 'GET',
colNames: ['Butiks kategori', 'Butik Navn', 'By', 'Sælger'],
colModel: [
{ name: 'Id', index: 'Id', width: 50 },
{ name: 'Butiks Kategori', index: 'StoreId', width: 200, edittype: 'text', align: 'center', editable: false },
{ name: 'Buttiks Navn', index: 'StoreName', width: 200, edittype: 'text', align: 'center', editable: false },
{ name: 'Country', index: 'Country', width: 80, sortable: true, editable: true, edittype: "select", editoptions: { value: data }}],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("GridSave")',
rowNum: 50000,
rowList: [5, 10, 20, 50],
pager: '#page',
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
height: "500px",
imgpath: '/scripts/themes/base/images'
});
jQuery("#list").jqGrid('navGrid', "#page", { edit: false, add: false, del: false });
});
}
</script>
P.S. Ill link code as soon as i am back home
UPDATED: Thanks for an answer, im new to jq, so im making alot of mistakes ofc., but now im back to where i was before, the dropdownlist is not populated with data. i cleaned up the code as u said, so it looks like this now:
btw. The ConstructSelect return a list of Strings
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("GetStoreList")',
ajaxSelectOptions: { type: "POST", dataType: "json" },
datatype: 'json',
mtype: 'GET',
colNames: ['Butiks kategori', 'Butik Navn', 'By', 'Sælger'],
colModel: [
{ name: 'Kategori', index: 'Kategori', width: 50, key: false},
{ name: 'Navn', index: 'Navn', align: 'center', editable: false },
{ name: 'By', index: 'By', align: 'center', editable: false },
{ name: 'Sælger', index: 'Sælger', editable: true, edittype: "select",
editoptions: { dataUrl: '#Url.Action("ConstructSelect")',
buildSelect: function (data) {
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
var ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + "</select>";
}
}
}],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("GridSave")',
rowNum: 50000,
rowList: [5, 10, 20, 50],
pager: '#page',
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
height: "900px"
});
jQuery("#list").jqGrid('navGrid', "#page", {edit:false, add:false, del:false});
});
Okay, slight modifications was needed to get it working :
var response = typeof(data) === "string" ? jQuery.parseJSON(data.responseText):data;
aparently u have to tell buildselect that the data u want to modify is String
But i still have the problem that it doesnt show from begining which sellers is already selected!
Okay after restart it mysticly worked... it is solved now
What you need to do is to use
editoptions: { dataUrl: '#Url.Action("ConstructSelect")' }
instead of
editoptions: { value: data }
Depend on the format of the output of the action ConstructSelect you can need to use an additional property buildSelect of the editoptions. jqGrid expected that the server response on the HTTP 'GET' request of dataUrl will be HTML fragment which represent <select>. For example:
<select>
<option value="de">Germany</option>
<option value="us">USA</option>
</select>
If the server return other formatted data, like JSON data
["Germany","USA"]
or
[{"code":"de","display":"Germany"},{"code":"us","display":"USA"}]
you can write JavaScript function which convert the server response to the HTML fragment of the <select> and set the value of the property buildSelect to the function.
In the answer you will find an example of the function.
If your action support only HTTP POST and no GET you will have to use ajaxSelectOptions: { type: "POST" } parameter additionally, to overwrite the type of the corresponding ajax requests. In the same way you can overwrite other ajax parameters. For example you can use
ajaxSelectOptions: { type: "POST", dataType: "json"}
(defaults are type : "GET" and dataType: "html")
Some other small remarks to the code:
you should not place $(document).ready(function () { inside of another $(document).ready(function () {.
You use 'Id' instead of 'id'. So jqGrid will not find the id property. You can a) rename
'Id' to 'id' b) include additional parameter jsonReader: {id: 'Id'} c) include additional property key: true in the definition of the column 'Id'. Any from the ways will solve the described problem.
You can remove default properties like edittype: 'text', sortable: true or editable: false. See jqGrid documentation which describes the default values of all colModel properties.
You should remove imgpath parameter of jqGrid. The parameter is not exist since many many versions of jqGrid (see here).

Cant get JQGrid loadComplete event to fire

I'm trying to simulate a click on the first cell after the grid is loaded. I already know how to accomplish this, but for some reason I can't get the "loadComplete" event to fire. I have added a simple function with a single alert to try it out, but even though the page loads with no problem, I'm not getting the alert (and debugging shows the function is never called).
"gridComplete" is not working either.
I am using jgGrid 3.8.2
Any idea on what I'm doing wrong? I have posted my code below:
$(document).ready(function () {
$("#grid").jqGrid(
{
datatype: function () {
$.ajax(
{
type: "POST",
url: "Default.aspx/GetListOfPersons",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (jsondata, stat) {
if (stat == "success")
jQuery("#grid")[0].addJSONData(JSON.parse(jsondata.d));
else
alert("error");
}
});
},
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "Id"
},
colModel: //Columns
[
{ name: 'FirstName', index: 'FirstName', width: 200, align: 'Left', label: 'First Name', editable: true },
{ name: 'LastName', index: 'LastName', width: 300, align: 'Left', label: 'Last Name', editable: true },
{ name: 'Age', index: 'Age', width: 50, align: 'Right', label: 'Age', editable: true }
],
caption: "Personas",
cellEdit: true,
cellsubmit: 'clientArray',
pager: "#pager",
loadComplete: function () { alert("load complete"); }
}
).navGrid('#pager', { edit: false, add: false, del: false, search: false }).navButtonAdd('#pager',
{
caption: "Save",
onClickButton: function () {
var ret = $("#grid").getChangedCells('dirty');
var ret2 = JSON.stringify(ret);
$.ajax(
{
type: "post",
url: "Default.aspx/GetChangesBack",
data: '{"o":' + ret2 + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}
);
},
position: "last"
}
);
}
);
Because you are calling $.ajax yourself, I don't think loadComplete should fire.
gridComplete should work, though.

Resources