JQGrid MultiSelect Filter option populate based on column's distinct value(part-II) - jqgrid

I am using this to fill multiselect filter value based on those are present in available rows for particular column.
I am facing below issue when going to delete selected row i.e. say I have deleted the first row, after deletion multiselect filter should recalculate the value based on those are present in available rows for particular column(for SkillCategory). We can see after deletion first row still "Data" value is available for SkillCategory multiselect filter.
How can I recalculate multiselect filter value after deleting row/add/update?
<script type="text/javascript">
function loadCompleteHandler1() {
initializeGridFilterValueSupply();
}
jQuery(function () {
$.extend(true, $.jgrid.search, {
beforeShowForm: function ($form) {
$form.closest(".ui-jqdialog").position({
of: window,
at: "center center",
my: "center center"
});
}
});
$.extend($.jgrid.edit, { viewPagerButtons: false });
$grid = $("#listTableSupply"),
myDefaultSearch = "cn",
getColumnIndexByName = function (columnName) {
var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i += 1) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
},
modifySearchingFilter = function (separator) {
var i, l, rules, rule, parts, j, group, str, iCol, cmi, cm = this.p.colModel,
filters = $.parseJSON(this.p.postData.filters);
if (filters && filters.rules !== undefined && filters.rules.length > 0) {
rules = filters.rules;
for (i = 0; i < rules.length; i++) {
rule = rules[i];
iCol = getColumnIndexByName.call(this, rule.field);
cmi = cm[iCol];
if (iCol >= 0 &&
((cmi.searchoptions === undefined || cmi.searchoptions.sopt === undefined)
&& (rule.op === myDefaultSearch)) ||
(typeof (cmi.searchoptions) === "object" &&
$.isArray(cmi.searchoptions.sopt) &&
cmi.searchoptions.sopt[0] === rule.op)) {
// make modifications only for the 'contains' operation
parts = rule.data.split(separator);
if (parts.length > 1) {
if (filters.groups === undefined) {
filters.groups = [];
}
group = {
groupOp: 'OR',
groups: [],
rules: []
};
filters.groups.push(group);
for (j = 0, l = parts.length; j < l; j++) {
str = parts[j];
if (str) {
// skip empty '', which exist in case of two separaters of once
group.rules.push({
data: parts[j],
op: rule.op,
field: rule.field
});
}
}
rules.splice(i, 1);
i--; // to skip i++
}
}
}
this.p.postData.filters = JSON.stringify(filters);
}
},
dataInitMultiselect = function (elem) {
setTimeout(function () {
var $elem = $(elem), id = elem.id,
inToolbar = typeof id === "string" && id.substr(0, 3) === "gs_",
options = {
selectedList: 2,
height: "auto",
checkAllText: "all",
uncheckAllText: "no",
noneSelectedText: "Any",
open: function () {
var $menu = $(".ui-multiselect-menu:visible");
$menu.width("auto");
return;
}
},
$options = $elem.find("option");
if ($options.length > 0 && $options[0].selected) {
$options[0].selected = false; // unselect the first selected option
}
if (inToolbar) {
options.minWidth = 'auto';
}
//$elem.multiselect(options);
$elem.multiselect(options).multiselectfilter({ placeholder: '' });
$elem.siblings('button.ui-multiselect').css({
width: inToolbar ? "98%" : "100%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}, 50);
};
jQuery("#listTableSupply").jqGrid({
url: 'HttpHandler/SupplyHandler.ashx',
ajaxSelectOptions: { cache: false },
postData: { ActionPage: 'TransportType', Action: 'Fill' },
datatype: 'json',
mtype: 'GET',
colNames: ['SupplyId', 'Account', 'AccountPOC', 'COE', 'Type', 'Location', 'EmpId', 'EmpName', 'Designation', 'AvailabilityDate', 'AvailabilityMonth', 'Exp', 'SkillCategory', 'PrimarySkill', 'SecondarySkill', 'OtherSkill', 'Role', 'VisaStatus', 'Country', 'Comments'],
colModel: [
{ name: 'SupplyId', index: 'SupplyId', width: '5%', align: 'center', sortable: true, resizable: true, hidden: true },
{
name: 'Account', index: 'Account', width: '10%', sortable: true, resizable: true, stype: 'select'
},
{ name: 'AccountPOC', index: 'AccountPOC', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'COE', index: 'COE', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'Type', index: 'Type', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'Location', index: 'Location', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{ name: 'EmpId', index: 'EmpId', width: '5%', sortable: true, resizable: true, hidden: true },
{ name: 'EmpName', index: 'EmpName', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'Designation', index: 'Designation', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'AvailabilityDate', index: 'AvailabilityDate', width: '5%', sortable: true, search: true, resizable: true, stype: 'select'
},
{ name: 'AvailabilityMonth', index: 'AvailabilityMonth', width: '5%', sortable: true, resizable: true, hidden: true },
{
name: 'Experience', index: 'Experience', width: '5%', sortable: true, resizable: true, search: true, stype: 'select'
},
{
name: 'SkillCategory', index: 'SkillCategory', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'PrimarySkill', index: 'PrimarySkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'SecondarySkill', index: 'SecondarySkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'OtherSkill', index: 'OtherSkill', width: '5%', sortable: true, resizable: true, stype: 'select'
},
{
name: 'CurrentRole', index: 'CurrentRole', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{
name: 'VisaStatus', index: 'VisaStatus', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{
name: 'Country', index: 'Country', width: '5%', sortable: true, resizable: true,
stype: 'select'
},
{ name: 'Comments', index: 'Comments', width: '5%', search: false, sortable: false, resizable: true },
],
width: '1192',
height: '300',
loadonce: true,
pager: '#pagerSupply',
gridview: true,
rowNum: 15,
rowList: [15, 30, 45],
rowTotal: 5000,
sortorder: 'asc',
ignoreCase: true,
sortname: 'Account',
viewrecords: true,
rownumbers: true,
toppager: true,
caption: 'Supply',
emptyrecords: "No records to view",
loadtext: "Loading...",
refreshtext: "Refresh",
refreshtitle: "Reload Grid",
loadComplete: loadCompleteHandler1,
ondblClickRow: function (rowid) {
jQuery(this).jqGrid('viewGridRow', rowid);
},
beforeRequest: function () //loads the jqgrids state from before save
{
modifySearchingFilter.call(this, ',');
}
}).jqGrid('bindKeys');
$('#listTableSupply').bind('keydown', function (e) {
if (e.keyCode == 38 || e.keyCode == 40) e.preventDefault();
});
//setSearchSelect("SkillCategory");
$('#listTableSupply').jqGrid('navGrid', '#pagerSupply', {
cloneToTop: true,
refresh: true, refreshtext: "Clear Filter", edit: false, add: false, del: true, search: false
}, {}, {}, {//Del
closeOnEscape: true, //Closes the popup on pressing escape key
drag: true,
recreateForm: true,
//closeAfterEdit: true,
url: 'HttpHandler/SupplyHandler.ashx',
delData: {
ActionPage: 'TransportType', Action: 'Delete',
SupplyId: function () {
var sel_id = $('#listTable').jqGrid('getGridParam', 'selrow');
var value = $('#listTable').jqGrid('getCell', sel_id, 'SupplyId');
return value;
}
},
afterShowForm: function ($form) {
$form.closest(".ui-jqdialog").position({ of: window, my: "center center", at: "center center" });
//$form.closest(".ui-jqdialog").position({of: window,at: "center center",my: "left top"});
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
//$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after del
return [true, '']
}
else {
if (response.responseText == "Record Successfully Deleted!!!") {
//$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
var myInfo = '<div class="ui-state-highlight ui-corner-all">' +
'<span class="ui-icon ui-icon-info" ' +
'style="float: left; margin-right: .3em;"></span>' +
'<span>Record Successfully Deleted!!!</span></div>';
var infoTR = $("table#TblGrid_listTable>tbody>tr.tinfo");
infoTD = infoTR.children("td.topinfo");
infoTD.html(myInfo);
infoTR.show();
setTimeout(function () {
infoTD.children("div").fadeOut('slow',
function () {
infoTR.hide();
});
}, 8000);
initializeGridFilterValueSupply();
return [true, '']
}
else {
return [false, response.responseText]//Captures and displays the response text on th Del window
}
}
}
}, {
multipleSearch: true,
multipleGroup: true,
recreateFilter: true
});
jQuery("#listTableSupply").jqGrid('navButtonAdd', '#listTableSupply_toppager_left', { // "#list_toppager_left"
caption: "Refresh",
buttonicon: 'ui-icon-refresh',
onClickButton: function () {
$("#listTableSupply").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid", [{ page: 1 }]);
initializeGridFilterValueSupply();
}
});
jQuery("#listTableSupply").jqGrid('navButtonAdd', '#pagerSupply', { // "#list_toppager_left"
caption: "Refresh",
buttonicon: 'ui-icon-refresh',
onClickButton: function () {
$("#listTableSupply").jqGrid("setGridParam", { datatype: "json" }).trigger("reloadGrid", [{ page: 1 }]);
initializeGridFilterValueSupply();
}
});
});
//]]>
</script>
<script type="text/javascript">
initializeGridFilterValueSupply = function () {
jQuery("#listTableSupply").jqGrid('destroyGroupHeader');
setSearchSelect("Account", jQuery("#listTableSupply"));
setSearchSelect("COE", jQuery("#listTableSupply"));
setSearchSelect("AccountPOC", jQuery("#listTableSupply"));
setSearchSelect("Type", jQuery("#listTableSupply"));
setSearchSelect("Location", jQuery("#listTableSupply"));
setSearchSelect("Designation", jQuery("#listTableSupply"));
setSearchSelect("EmpName", jQuery("#listTableSupply"));
setSearchSelect("AvailabilityDate", jQuery("#listTableSupply"));
setSearchSelect("Experience", jQuery("#listTableSupply"));
setSearchSelect("SkillCategory", jQuery("#listTableSupply"));
setSearchSelect("PrimarySkill", jQuery("#listTableSupply"));
setSearchSelect("SecondarySkill", jQuery("#listTableSupply"));
setSearchSelect("OtherSkill", jQuery("#listTableSupply"));
setSearchSelect("CurrentRole", jQuery("#listTableSupply"));
setSearchSelect("VisaStatus", jQuery("#listTableSupply"));
setSearchSelect("Country", jQuery("#listTableSupply"));
jQuery("#listTableSupply").jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: true,
defaultSearch: myDefaultSearch,
beforeClear: function () {
$(this.grid.hDiv).find(".ui-search-toolbar .ui-search-input>select[multiple] option").each(function () {
this.selected = false; // unselect all options
});
$(this.grid.hDiv).find(".ui-search-toolbar button.ui-multiselect").each(function () {
$(this).prev("select[multiple]").multiselect("refresh");
}).css({
width: "98%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}
});
jQuery("#listTableSupply").jqGrid('setGridHeight', 300);
}
</script>

I got my answer.
I need to use destroyFilterToolbar to destroy the filter toolbar and then create the toolbar one more time using filterToolbar.
initializeGridFilterValueDemand = function () {
//jQuery("#listTableSupply").jqGrid('destroyGroupHeader');
setSearchSelect("AccountName", jQuery("#listTableDem"));
setSearchSelect("COE", jQuery("#listTableDem"));
setSearchSelect("DemandType", jQuery("#listTableDem"));
setSearchSelect("Location", jQuery("#listTableDem"));
setSearchSelect("Designation", jQuery("#listTableDem"));
setSearchSelect("Experience", jQuery("#listTableDem"));
setSearchSelect("ExpectedRole", jQuery("#listTableDem"));
setSearchSelect("SkillCategory", jQuery("#listTableDem"));
setSearchSelect("PrimarySkill", jQuery("#listTableDem"));
setSearchSelect("SecondarySkill", jQuery("#listTableDem"));
setSearchSelect("OtherSkill", jQuery("#listTableDem"));
setSearchSelect("RequiredDate", jQuery("#listTableDem"));
setSearchSelect("CriticalFlag", jQuery("#listTableDem"));
setSearchSelect("ConfidenceFactor", jQuery("#listTableDem"));
setSearchSelect("HiringSOId", jQuery("#listTableDem"));
**jQuery("#listTableDem").jqGrid("destroyFilterToolbar");**
jQuery("#listTableDem").jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: true,
defaultSearch: myDefaultSearch,
beforeClear: function () {
$(this.grid.hDiv).find(".ui-search-toolbar .ui-search-input>select[multiple] option").each(function () {
this.selected = false; // unselect all options
});
$(this.grid.hDiv).find(".ui-search-toolbar button.ui-multiselect").each(function () {
$(this).prev("select[multiple]").multiselect("refresh");
}).css({
width: "98%",
marginTop: "1px",
marginBottom: "1px",
paddingTop: "3px"
});
}
});
jQuery("#listTableDem").jqGrid('setGridHeight', 300);
}
And I am calling it in loadComplete event.
Update:
This will not going to work if we use destroyGroupHeader

Related

JQGrid search functionality works if two same name column interchanges

am using JQGrid and enabled Search to true . everything is working fine.
scenario: there are two budget column one is for footer total and another is for column
$("#BudgetGrid").jqGrid({
datatype: 'local',
data: JSON.parse($('#JsonData').val()),
colModel: [
{
name: 'BudgetId',
hidden: true,
classes: 'budgetid'
},
{
name: 'Month',
hidden: true
},
{
name: 'MonthInWords',
resizable: true,
//align: 'center',
label: 'Month',
ignoreCase: true
},
{
name: 'Budget',
resizable: true,
align: 'center',
label: 'Budget',
ignoreCase: true,
formatter: function (cellvalue, options, rowObject, rowid) {
return '<input type="textbox" class="form-control number" id="budget" value=\"' + rowObject.Budget + '\"></input>';
}
},
{
name: 'Budget',
resizable: true,
label: 'Budget',
ignoreCase: true,
hidden: true,
sorttype: 'number',
summaryType: 'sum',
formatter: 'integer',
formatoptions: {
decimalSeparator: '.', decimalPlaces: 2, suffix: '', thousandsSeparator: ',', prefix: ''
}
}
],
loadonce: true,
pager: "#BudgetGridPager",
viewrecords: true,
ignoreCase: true,
rowNum: 12,
footerrow: true,
userDataOnFooter:true,
gridComplete: function () {
var objRows = $("#BudgetGrid tbody tr");
var objHeader = $("#BudgetGrid tbody tr td");
if (objRows.length > 1) {
var objFirstRowColumns = $(objRows[1]).children("td");
for (i = 0; i < objFirstRowColumns.length; i++) {
$(objFirstRowColumns[i]).css("width", $(objHeader[i]).css("width"));
}
}
}
, loadComplete: function (data) {
var $grid = $('#BudgetGrid');
//debugger;
$grid.jqGrid('footerData', 'set', { MonthInWords: "Total" });
$grid.jqGrid('footerData', 'set', { 'Budget': ($grid.jqGrid('getCol', 'Budget', false, 'sum')).toFixed(3) }, false);
}
});
$("#BudgetGrid").jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: false,
defaultSearch: "cn"
});
when i write hidden budget up search column search wont work
but when i write budget without hidden and next budget hidden , search works fine.
can anyone please say the reason behind it

JqGrid paging with lots of grids

I have a single page ASP.Net web forms application. And lots of grids. In my application, there is some links to hide or show grids. The problem is, when i start the application, the pagination of the displayed grid is working properly. (I tried this for each grid). But when I Click the link for hide a grid and show another grid, paging does not working. The grid initialization is;
$('#tblApplicationSettings').jqGrid({
url: cms.util.getAjaxPage(),
cellLayout: cms.theme.list.cellLayout,
hoverrows: false,
forceFit: true,
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "",
id: "0"
},
width: 900,
height: 400,
datatype: 'local',
colNames: ['SettingId',
'Description',
'Name',
'Value',
'ServerId',
'IsReadOnly',
''
],
colModel: [
{
name: 'SettingId',
index: 'SettingId',
hidden: true
},
{
name: 'Description',
index: 'Description',
search: false,
editable: true,
sortable: false,
width: 150,
inlineEditable: true
},
{
name: 'Name',
index: 'Name',
search: false,
editable: false,
sortable: false,
width: 150,
inlineEditable: false
},
{
name: 'Value',
index: 'Value',
search: false,
editable: true,
sortable: false,
width: 250,
inlineEditable: true,
},
{
name: 'ServerId',
index: 'ServerId',
search: false,
editable: true,
sortable: false,
width: 150,
formatter: 'select',
edittype: 'select',
editoptions: {
value: options,
},
inlineEditable: true
},
{
name: 'IsReadOnly',
index: 'IsReadOnly',
hidden: true
},
{
name: 'JsUsage',
index: 'JsUsage',
search: false,
editable: true,
sortable: false,
width: 150,
inlineEditable: true
},
],
onSelectRow: function (id) {
if (id && id !== lastSelection) {
jQuery('#grid').jqGrid('restoreRow', lastSelection);
lastSelection = id;
}
var columnModel = $('#grid').getGridParam('colModel');
var colNames = new Array();
$.each(columnModel, function (index, column) {
colNames.push(column.name);
if (isReadOnly || !column.inlineEditable) {
column.editable = false;
}
else {
column.editable = true;
}
if (column.edittype == "select") {
column.editoptions.dataEvents = [{
type: 'change',
fn: function (e) {
var newServerId = $(this).val();
that.isServerIdChanged = true;
if (newServerId == "null") {
}
}
}]
}
});
var row = $('#grid').getRowData(id);
var isReadOnly = row.IsReadOnly == "true" ? true : false;
if (isReadOnly) {
alert("row is not editable");
return null;
}
jQuery("#grid").jqGrid('editRow', id, {
keys: true,
extraparam: {
dataType: 'updateSetting',
colNames: JSON.stringify(colNames),
settingName: row.Name,
settingId: row.SettingId
},
successfunc: function (result) {
$("#grid").trigger('reloadGrid');
}
});
},
editurl: '/Ajax.ashx',
rowNum: 25,
direction: "ltr",
scroll: 1,
gridview: true,
pager: '#divPager',
viewrecords: true,
});
$('#grid').setGridParam({ datatype: "json", postData: { dataType: 'getSettings' } });
$('#grid').jqGrid('navGrid', '#divPager', { edit: false, add: false, del: false, search: false, refresh: false });
$('#grid').trigger('reloadGrid');
like this for all grids. I need tips or helps. Thanks.

jqSubGrid not loading with data

I do realize many have asked this same question. I have tried all other suggestions and have had no success. I know for sure its something I am overlooking and wanted a second set of eyes to help me. Thanks in advance!!
My problem is that the primary grid loads find. Its the sub grid thats the problem.
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#PositionsGrid").jqGrid({
url: '/Position/GetPositions?projectid=#Model.ID',
datatype: 'json',
mtype: 'POST',
colNames: ['PositionID', 'ID', 'Job', 'Band', 'Start Date', 'End Date','Current Assignee','Terminated Worker','Status'],
colModel: [
{ name: 'PositionID', index: 'PositionID', width: 20, align: 'left', hidden: true, sortable: false, search: false,key:true },
{ name: 'DisplayID', index: 'DisplayID', width: 50, align: 'left' },
{ name: 'JobTitle', index: 'JobTitle', width: 100, align: 'left' },
{ name: 'Band', index: 'Band', width: 50, align: 'left' },
{ name: 'StartDate', index: 'StartDate', width: 50, align: 'left', searchoptions: { sopt: ['cn'], dataInit: datePick} },
{ name: 'EndDate', index: 'EndDate', width: 50, align: 'left', searchoptions: { sopt: ['cn'], dataInit: datePick} },
{ name: 'CurrentWorker', index: 'CurrentWorker', width: 100, align: 'left' },
{ name: 'TerminatedWorker', index: 'TerminatedWorker', width: 100, align: 'left' },
{ name: 'Status', index: 'Action', width: 50, align: 'left', search: false}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'PositionID',
sortorder: "asc",
viewrecords: true,
autowidth: true,
subGrid: true,
subGridRowExpanded: showDetails
});
$('#PositionsGrid').jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
$("#PositionGrid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false, refresh: true });
});
datePick = function (elem) {
$(elem).datepicker({ dateFormat: "mm/dd/yy", onSelect: function (dateText, inst) { $("#grid")[0].triggerToolbar(); } });
};
function showDetails(subgrid_id, row_id) {
showSubGrid_AssignmentsGrid(subgrid_id, row_id, "<br><b>Worker History</b><br><br>", "AssignmentsGrid");
}
function showSubGrid_AssignmentsGrid(subgrid_id, row_id, message, suffix) {
var subgrid_table_id;
subgrid_table_id = subgrid_id + "_t";
if (message) jQuery('#' + subgrid_id).append(message);
if (message) jQuery('#' + subgrid_id).append(message);
jQuery("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table>");
jQuery("#" + subgrid_table_id).jqGrid({
url: "Position/GetAssignmentsByPosition?positionid=" + row_id,
datatype: "json",
colNames: ['AssignID', 'JobReqNum', 'WorkerName', 'StartDate', 'EndDate','Status'],
colModel: [
{ name: "AssignID", index: "AssignID", width: 80},
{ name: "JobReqNum", index: "JobReqNum", width: 130 },
{ name: "WorkerName", index: "WorkerName", width: 80, align: "right" },
{ name: "StartDate", index: "StartDate", width: 80, align: "right" },
{ name: "EndDate", index: "EndDate", width: 100, align: "right" },
{ name: "Status", index: "Status", width: 100, align: "right" }
],
height: '100%',
rowNum: 20,
sortname: 'AssignID',
sortorder: "asc"
});
}
</script>
the controller action that loads the subgrid is below
public JsonResult GetAssignmentsByPosition(int positionid)
{
ProjPosition position = uow.PositionRepository.GetPosition(positionid);
var jsonRows = position.ProjPositionAssignments.AsEnumerable()
.Select(a => new
{
cell = new string[] { a.ID.ToString(),
a.JobReqNum == null ? "" :a.JobReqNum,
a.Worker == null ? "" : a.Worker.FullName,
(a.StartDate == null) ? "" : ((DateTime)a.StartDate).ToString("MM/dd/yyyy"),
(a.EndDate == null) ? "" : ((DateTime)a.EndDate).ToString("MM/dd/yyyy"),
(a.Status == null ? "Active" : StatusDictionary.AssignmentStatusDictionary[a.Status])
}
})
.ToArray();
var jsonData = new
{
rows = jsonRows
};
return Json(jsonData);
}
You also need to pass to jqgrid:
page = numberOfPages
records = totalRecords,
I personally use something like:
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
rows = (
from item in pagedQuery
select new
{
cell = new string[] {
item.value1,
item.value2, ....
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);

Jqgrid - subgrid data not loading

I'm trying to load the subgrid data from the main grid. The main grid loads fine but When I click on a row the subgrid data does not load.
Don't know what I'm missing. Please help.
Below is the code I'm using.
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
var mydata = [],
grid = $("#list");
var mainGridPrefix = "s_";
grid.jqGrid({
url: '${recordsUrl}',
datatype: 'json',
ignoreCase: true,
mtype: 'GET',
colNames: ['Global Search', 'serverId', 'DeviceName', 'Description', 'Console', 'OS', 'Business Unit', 'Model', 'Manufacturer', 'Serial Number', 'LifeCycle', 'Tier'],
colModel: [{
name: 'globalSearch',
index: 'globalSearch',
width: 50,
hidden: true,
searchoptions: {
searchhidden: true
}
}, {
name: 'serverId',
index: 'serverId',
width: 10,
hidden: true
}, {
name: 'deviceName',
index: 'deviceName',
width: 50
}, {
name: 'serverDesc',
index: 'serverDesc',
width: 70
}, {
name: 'console',
index: 'console',
width: 50
}, {
name: 'groupName',
index: 'groupName',
width: 40
}, {
name: 'businessUnit',
index: 'businessUnit',
width: 30
}, {
name: 'model',
index: 'model',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'manufacturer',
index: 'manufacturer',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'serialNumber',
index: 'serialNumber',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'lifeCycle',
index: 'lifeCycle',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'tier',
index: 'tier',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}],
postData: {},
rowNum: 10,
rowList: [10, 20, 40, 60],
height: 'auto',
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'deviceName',
viewrecords: true,
sortorder: "asc",
caption: "Records",
emptyrecords: "Empty records",
idPrefix: mainGridPrefix,
loadonce: true,
loadComplete: function () {},
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "serverId"
},
subGrid: true,
beforeProcessing: function (data) {
var rows = data.rows,
l = rows.length,
i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.apps) {
subgrids[item.id] = item.apps;
}
}
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: ["App Id", "Desc"],
colModel: [{
name: "appId"
}, {
name: "applicationDesc"
}],
sortname: "applicationDesc",
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
jsonReader: {
repeatitems: false,
id: "appId"
},
gridview: true,
idPrefix: rowId + "_"
});
}
});
$("#search").click(function () {
var searchFiler = $("#filter").val(),
f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, {
filters: ""
});
}
f = {
groupOp: "OR",
rules: []
};
f.rules.push({
field: "globalSearch",
op: "cn",
data: searchFiler
});
f.rules.push({
field: "deviceName",
op: "cn",
data: searchFiler
});
grid[0].p.search = true;
$.extend(grid[0].p.postData, {
filters: JSON.stringify(f)
});
grid.trigger("reloadGrid", [{
page: 1,
current: true
}]);
});
grid.jqGrid('navGrid', '#pager', {
edit: false,
add: false,
del: false,
search: true,
view: true
}, {}, {}, {}, { // search
sopt: ['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}, { // vew options
beforeShowForm: function (form) {
$("tr#trv_id", form[0]).show();
},
afterclickPgButtons: function (whichbutton, form, rowid) {
$("tr#trv_id", form[0]).show();
}
});
grid.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-plus",
onClickButton: addRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Edit",
buttonicon: "ui-icon-pencil",
onClickButton: editRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Delete",
buttonicon: "ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title: "",
cursor: "pointer"
});
});
//]]>
you forgot to add the index: information for the colModel in the subgrid, you also need to pay attention to capitalization if the name is capitalized then so should be the index, that way jqgrid knows that where it needs to put the data. Here is the fixed code and also a link to a working example
//<![CDATA[
$(document).ready(function () {
var mydata = [{
globalsearch: "1",
serverId: "Test Name1",
deviceName: "Test Address1",
Console: "Test Date1"
}, {
globalsearch: "2",
serverId: "Test Name2",
deviceName: "Test Address2",
Console: "Test Date2"
}, {
globalsearch: "3",
serverId: "blah",
deviceName: "hello",
Console: "basketball"
}];
grid = $("#list");
var mydata2 = [{
AppId: "1",
Desc: "Test Name1"
}, {
AppId: "2",
Desc: "Test Name2"
}, {
AppId: "3",
Desc: "blah"
}];
var mainGridPrefix = "s_";
grid.jqGrid({
datatype: 'local',
data: mydata,
colNames: ['globalsearch', 'serverId', 'deviceName', 'Description', 'Console', 'OS', 'Business Unit', 'Model', 'Manufacturer', 'Serial Number', 'LifeCycle', 'Tier'],
colModel: [{
name: 'globalsearch',
index: 'globalsearch',
width: 50,
}, {
name: 'serverId',
index: 'serverId',
width: 10,
hidden: false
}, {
name: 'deviceName',
index: 'deviceName',
width: 50
}, {
name: 'serverDesc',
index: 'serverDesc',
width: 70
}, {
name: 'Console',
index: 'Console',
width: 50
}, {
name: 'groupName',
index: 'groupName',
width: 40
}, {
name: 'businessUnit',
index: 'businessUnit',
width: 30
}, {
name: 'model',
index: 'model',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'manufacturer',
index: 'manufacturer',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'serialNumber',
index: 'serialNumber',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'lifeCycle',
index: 'lifeCycle',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}, {
name: 'tier',
index: 'tier',
width: 30,
editable: true,
editrules: {
required: true,
edithidden: true
},
hidden: true,
editoptions: {
dataInit: function (element) {
$(element).attr("readonly", "readonly");
}
}
}],
rowNum: 10,
rowList: [10, 20, 40, 60],
rownumbers: true,
pager: '#pager',
sortname: 'deviceName',
viewrecords: true,
sortorder: "asc",
caption: "Records",
height: 'auto',
autowidth: true,
loadComplete: function () {},
subGrid: true,
beforeProcessing: function (data) {
var rows = data.rows,
l = rows.length,
i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.apps) {
subgrids[item.id] = item.apps;
}
}
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: mydata2,
colNames: ["AppId", "Desc"],
colModel: [{
name: "AppId",
index: "AppId"
}, {
name: "Desc",
index: "Desc"
}],
sortname: "applicationDesc",
height: "100%",
rowNum: 10000,
autoencode: true,
autowidth: true,
jsonReader: {
repeatitems: false,
id: "appId"
},
gridview: true,
idPrefix: rowId + "_"
});
}
});
$("#search").click(function () {
var searchFiler = $("#filter").val(),
f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, {
filters: ""
});
}
f = {
groupOp: "OR",
rules: []
};
f.rules.push({
field: "globalSearch",
op: "cn",
data: searchFiler
});
f.rules.push({
field: "deviceName",
op: "cn",
data: searchFiler
});
grid[0].p.search = true;
$.extend(grid[0].p.postData, {
filters: JSON.stringify(f)
});
grid.trigger("reloadGrid", [{
page: 1,
current: true
}]);
});
grid.jqGrid('navGrid', '#pager', {
edit: false,
add: false,
del: false,
search: true,
view: true
}, {}, {}, {}, { // search
sopt: ['cn', 'eq', 'ne', 'lt', 'gt', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}, { // vew options
beforeShowForm: function (form) {
$("tr#trv_id", form[0]).show();
},
afterclickPgButtons: function (whichbutton, form, rowid) {
$("tr#trv_id", form[0]).show();
}
});
grid.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-plus",
onClickButton: addRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Edit",
buttonicon: "ui-icon-pencil",
onClickButton: editRow,
position: "last",
title: "",
cursor: "pointer"
});
grid.navButtonAdd('#pager', {
caption: "Delete",
buttonicon: "ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title: "",
cursor: "pointer"
});
});
//]]>
<table id="list"></table>
<div id="pager"></div>

jqgrid add window parameter

I'm uwsing MVC and jqgrid and I need to pass a value from dropdownlist to add or edit window. this is my code:
View:
jQuery("#grid").jqGrid({
url: '#Url.Content("~/")' + 'Something/GridData/',
datatype: "json",
mtype: 'POST',
colNames: ['Type', 'Product', 'Value1', 'Value2', 'Value3'],
colModel: [
{ name: 'parType', index: 'parType', width: 80, align: 'center', sortable: false, editable: true, search: false,
editrules: { required: true, number: true },
editoptions: {
dataEvents: [{
type: 'keyup',
fn: function (e) {
if (this.value.match(/\D/)) this.value = this.value.replace(/\D/g, '');
}
}]
}
},
{ name: 'parProduct', index: 'parProduct', width: 80, align: 'left', editable: true, edittype: "select",
editrules: { required: true },
editoptions: {
multiple: false,
size: 1,
dataUrl: '#Url.Content("~/")' + 'Something/List/',
buildSelect: function (data) {
var response = jQuery.parseJSON(data);
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.Value + '">' + ri.Text + '</option>';
}
}
return s + "</select>";
}
}
},
{ name: 'parValue1', index: 'parValue1', width: 80, align: 'right', sortable: false, editable: true, search: false,
editrules: { required: true, number: true },
editoptions: {
dataEvents: [{
type: 'keyup',
fn: function (e) {
if (this.value.match(/\D/)) this.value = this.value.replace(/\D/g, '');
}
}]
}
},
{ name: 'parValue2', index: 'parValue2', width: 80, align: 'right', sortable: false, editable: true, search: false,
editrules: { required: true, number: true },
editoptions: {
dataEvents: [{
type: 'keyup',
fn: function (e) {
if (this.value.match(/\D/)) this.value = this.value.replace(/\D/g, '');
}
}]
}
},
{ name: 'parValue3', index: "parValue3", width: 80, align: 'right', editable: true,
editrules: { required: true },
editoptions: {
dataEvents: [{
type: 'blur',
fn: function (e) {
onBlurDecimal(this.id);
}
}]
}
}],
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery('#pager'),
sortname: '',
viewrecords: true,
sortorder: "asc",
caption: "Title",
height: 250,
width: 700
});
jQuery("#grid").jqGrid('navGrid', '#pager',
{ edit: false, add: true, del: true, search: false }, //options
{url: '#Url.Content("~/")' + 'Something/Add', closeAfterAdd: true, width: 500 }, // add options
{} // search options
);
#Html.ValidationSummary(False)
#Using Html.BeginForm()
<table>
<tr>
<td>
#Html.Label("ID_CONTRATANTE", "Contratante:")
#Html.DropDownListFor(Function(Model) Model.ID_CONTRATANTE, Nothing, New With {.style = "width:300px; visibility:visible", .class = "letraingreso"})
</td>
</tr>
</table>
End Using
Controller
Function Add(ByVal parType As Long, ByVal parProduct As Long, ByVal parValue1 As Long, ByVal parValue2 As Long, ByVal parValue3 As String) As ActionResult
Try
Dim varE As General1Entities = New General1Entities
Dim parIDContratante = Request.Form("ID_CONTRATANTE")
Dim var1 = New OBJECT With { _
.ID_TYPE = parProduct,
.ID_CONTRATANTE = parIDContratante,
.CODE = parType,
.VALUE1 = parValue1,
.VALUE2 = parValue2,
.VALUE3 = parValue3
}
varE.AddToOBJECTS(var1)
varE.SaveChanges()
Return Json(True)
Catch ex As Exception
Return Json(False)
End Try
End Function
As you can see, I need to get DDL value from main view (ID_CONTRATANTE) and put it into parIDContratante. Obviously the value return Nothing because the add window of jqgrid it's open. How can I send from parent view to add view window this value?
Regards.
Ok.... After looking for solutions I get it.
View (replace the old navGrid)
jQuery("#grid").jqGrid('navGrid', '#pager', {
edit: false, add: true, del: true, search: false, refresh: false
}, // general options
{
}, // options edit
{
url: '#Url.Content("~/")' + 'Something/WorkWith',
closeOnEscape: true,
closeAfterAdd: true,
width: 500,
modal: true,
addCaption: 'Nueva Tarifa',
reloadAfterSubmit: true,
beforeShowForm: function (frm) { $('#ID_CONTRATANTE').val(); },
//bottominfo: "Fields marked with (*) are required",
drag: true,
onclickSubmit: function (params) {
var ajaxData = {};
ajaxData = { parIDContratante: $("#ID_CONTRATANTE").val() };
return ajaxData;
}
}, // options add
{
url: "/Something/WorkWith"
}, // opciones para el dialogo de borrado
{
} // options search
);
Controller (replace old controller)
Function WorkWith(ByVal parFormCollection As FormCollection) As ActionResult
Try
Dim varE As General1Entities = New General1Entities
Dim operation = parFormCollection("oper")
If operation.Equals("add") Then
Dim var1 = New OBJECT With { _
.ID_TYPE = parFormCollection.Get("parProduct").ToString,
**.ID_CONTRATANTE = parFormCollection.Get("parIDContratante").ToString,**
.etc.....
}
varE.AddToOBJECTS(var1)
varE.SaveChanges()
ElseIf operation.Equals("edit") Then
ElseIf operation.Equals("del") Then
End If
Return Json(True)
Catch ex As Exception
' Do some error logging stuff, handle exception, etc.
Return Json(False)
End Try
End Function
I hope this helps some else.
Bye.

Resources