on jquery ajax call , unable to bind jqgrid data - jqgrid

I have 2 queries on binding jgGrid in MVC application..
1. I am unable to bind jsonData which is coming from controller on Success callback method
2. On button click i am loading jqgrid from server data, but when i click 2nd time it is not firing my server code(which is in controller), only first time it is executing the server code.
below is my javascript code
function buildGrid() {
// setup custom parameter names to pass to server prmNames: { search: "isSearch", nd: null, rows: "numRows", page: "page", sort: "sortField", order: "sortOrder" }, // add by default to avoid webmethod parameter conflicts postData: { searchString: '', searchField: '', searchOper: '' }, // setup ajax call to webmethod datatype: function(postdata) { mtype: "GET", $.ajax({ url: 'PageName.aspx/getGridData', type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(postdata), dataType: "json", success: function(data, st) { if (st == "success") { var grid = jQuery("#list")[0]; grid.addJSONData(JSON.parse(data.d)); } }, error: function() { alert("Error with AJAX callback"); } }); }, // this is what jqGrid is looking for in json callback jsonReader: { root: "rows", page: "page", total: "totalpages", records: "totalrecords", cell: "cell", id: "id", //index of the column with the PK in it userdata: "userdata", repeatitems: true }, colNames: ['Id', 'First Name', 'Last Name'], colModel: [ { name: 'id', index: 'id', width: 55, search: false }, { name: 'fname', index: 'fname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} }, { name: 'lname', index: 'lname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} } ], rowNum: 10, rowList: [10, 20, 30], pager: jQuery("#pager"), sortname: "fname", sortorder: "asc", viewrecords: true, caption: "Grid Title Here" }).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false }, {}, // default settings for edit {}, // add {}, // delete { closeOnEscape: true, closeAfterSearch: true}, //search {} ) });
var grid = $("#jQGrid"); $("#jQGrid").jqGrid({
//setup custom parameter names to pass to server
prmNames: { search: "isSearch", nd: null, rows: "numRows", page: "page", sort: "sortField", order: "sortOrder" },
// add by default to avoid webmethod parameter conflicts
postData: {
'ddlDSVIN': function () {
return $('#ddlDevice :selected').val();
},
'search': function () { return $("#searchId").val(); },
'OEMType': function () { return $('#ddlOEM :selected').text(); },
'frmDate': function () { return fromDate.toDateString(); },
'toDate': function () { return toDate.toDateString(); }
},
datatype: function(postdata) { mtype: "POST",
$.ajax({ url: '/DataIn/DataInSearchResult/', type: "POST", contentType: "application/json; charset=utf-8",
//data: postData,
datatype: "json",
success: function(data, st) {
if (st == "success") {
var grid = jQuery("#jQGrid")[0]; grid.addJSONData(JSON.parse(data.d));
var container = grid.parents('.ui-jqgrid-view');
$('#showgrid').show();
$('#jQGrid').show();
$('#divpager').show();
//container.find('.ui-jqgrid-hdiv, .ui-jqgrid-bdiv').show();
$("#hideandshow").show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
$("#hideandshow2").hide();
}
},
error: function(error) { alert("Error with AJAX callback" + error); } }); }, // this is what jqGrid is looking for in json callback
jsonReader: { root: "rows", page: "page", total: "totalpages", records: "totalrecords", cell: "cell", id: "id", //index of the column with the PK in it
userdata: "userdata", repeatitems: true
},
// url: '/DataIn/DataInSearchResult/',
colNames: ["PayloadCorrelationId", "Asset", "Type", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', index: 'CorrelationId', jsonmap: 'CorrelationId', hidden: true, width: 2, key: true },
// { name: "", index:'', editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "True:False" }, formatoptions: { disabled: false } },
{ name: 'Device', jsonmap: 'Device', width: '65px' },
{ name: 'Type', jsonmap: 'Type', width: '65px' },
{ name: 'DateReported', jsonmap: 'DateReported', width: '100px' },
{ name: 'ErrorType', jsonmap: 'ErrorType', width: '85px' },
{ name: 'Error', jsonmap: 'Error', width: '160px' },
{ name: 'Latitude', jsonmap: 'Latitude', width: '78px' }, { name: 'Longitude', jsonmap: 'Longitude', width: '78px' },
{ name: 'Payloadurl', jsonmap: 'Payloadurl', width: '180px', formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } }],
rowNum: 10, rowList: [10, 20, 30],
pager: jQuery("#divpager"), sortorder: "asc",
viewrecords: true, caption: "Grid Title Here"
}).jqGrid('navGrid', '#divpager', { edit: false, add: false, del: false }, {}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true}, //search
{ });
}
above method is called in document.ready function
$(documen).ready(function() {
("#buttonclick").click(function() {
buildGrid();
});
});
Can you please what was wrong with my code.. because i need to search on button click by passing the paramerter's to service method using postData {},but how to send this postData to url and bind the result to JqGrid.
thanks
Raj.

Usage of datatype as is not recommend way. Instead of that one can use datatype: "json". It informs that jqGrid should make for you the Ajax request using $.ajax method. One can use additional options of jqGrid to specify the options of the underlying $.ajax request.
The next problem you have in the code
$(documen).ready(function() {
$("#buttonclick").click(function() {
buildGrid();
});
});
The function buildGrid will be called every time if the user click on #buttonclick button. The problem is that you have initially the empty table
<table id="jQGrid"></table>
on your page, but after creating the grid (after the call $("#jQGrid").jqGrid({...});), the empty table will be converted in relatively complex structure of dives and tables (see the picture). The second call on non-empty table will be just ignored by jqGrid. It's the reason why the 2nd click on the button #buttonclick do nothing.
You can solve the problem in two ways. The first would be including $("#buttonclick").jqGrid("GridUnload"); before creating the grid. It would be destroy the grid and recreate the initial empty table. The second way os a little better. You can not destroy the grid at the second time, but to call $("#buttonclick").trigger("reloadGrid"); instead. It will force making new Ajax request to the server.
Minimal changing of your original code will follow us to about the following:
$(documen).ready(function() {
var $grid = $("#jQGrid");
$grid.jqGrid({
//setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
ddlDSVIN: function () {
return $('#ddlDevice').val();
},
search: function () {
return $("#searchId").val();
},
OEMType: function () {
return $('#ddlOEM')
.find("option")
.filter(":selected")
.text();
},
frmDate: function () {
return fromDate.toDateString();
},
toDate: function () {
return toDate.toDateString();
}
},
mtype: "POST",
url: '/DataIn/DataInSearchResult/',
datatype: "json",
ajaxGridOptions: { contentType: "application/json; charset=utf-8" },
loadComplete: function () {
$('#showgrid').show();
$('#jQGrid').show();
$('#divpager').show();
$("#hideandshow").show();
$("#lblTotal").html($(this).getGridParam("records") + " Results");
$("#hideandshow2").hide();
},
jsonReader: {
root: root: function (obj) {
return typeof obj.d === "string" ?
$.parseJSON(obj.d) :
obj.d;
},
total: "totalpages",
records: "totalrecords"
},
colNames: ["PayloadCorrelationId", "Asset", "Type", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
colModel: [
{ name: 'CorrelationId', hidden: true, width: 2, key: true },
// { name: "", index:'', editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "True:False" }, formatoptions: { disabled: false } },
{ name: 'Device', width: 65 },
{ name: 'Type', width: 65 },
{ name: 'DateReported', width: 100 },
{ name: 'ErrorType', width: 85 },
{ name: 'Error', width: 160 },
{ name: 'Latitude', width: 78 },
{ name: 'Longitude', width: 78 },
{ name: 'Payloadurl', width: 180, formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } }],
rowNum: 10,
rowList: [10, 20, 30],
pager: "#divpager",
sortorder: "asc",
viewrecords: true,
caption: "Grid Title Here"
}).jqGrid('navGrid', '#divpager', { edit: false, add: false, del: false },
{}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true} //search
);
$("#buttonclick").click(function() {
$grid.trigger("reloadGrid");
});
});

Related

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.

jqgrid subgrid is not loading data (no Ajax call sent to the server)

I have below setup jqgrid (v 4.6.0).
$(function () {
var JQGridDefaults = {
caption: '',
rowList: [10, 50, 100],
datatype: 'json',
height: '100%',
viewrecords: true,
mtype: 'GET',
colNames: ['Item Control No', 'Item Short Description', 'ID'],
colModel: [
{
name: 'ItemCode', index: 'ItemCode', search: true, width: 230, cellattr: makeCellContentWrap, searchoptions: {
sopt: ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn', 'nc'],
},
searchrules: {required: true}
},
{
name: 'ItemShortDesc', index: 'ItemShortDesc', search: true, width: 300, cellattr: makeCellContentWrap, searchoptions: {
sopt: ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn', 'nc'],
},
searchrules: {required: true }
}
//Hidden Fields - Start
{ name: 'ItemID', hidden: true, key: true }
//HiddenFields End
],
pager: '#GridPager',
rowNum: 10,
sortname: 'ItemCode',
sortorder: 'asc',
url: '/Items/List',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
userdata: "userdata",
subgrid: {
root: "rows",
repeatitems: false
}
},
//Sub Grid - Start
subGrid: true,
subGridBeforeExpand: function (pID, rowID) {
console.log("Before Expand");
var gridData = $(this).jqGrid('getRowData',rowID);
if (gridData.ItemCode == "") {
return false;
}
},
subGridUrl: '/Items/Details',
subGridModel: {
name: ['Revision', 'ItemCode'],
width: [50, 100],
align: ['center', 'center'],
mapping: ['Revision', 'ItemCode']
},
afterInsertRow: function (rowid, aData, rowelem) {
// Remove the subgrid plus button except for rows that have exceptions
if (aData.ItemCode == "") {
$('#' + rowid).children("td.sgcollapsed").unbind();
$('#' + rowid).children("td.sgcollapsed").html("");
}
}
//Sub Grid - END
};
var JQGridSearchDefaults = {
multipleSearch: true,
recreateFilter: true,
showQuery: true,
closeAfterSearch: true,
closeAfterReset: true,
searchOnEnter: true,
closeOnEscape:true,
width: 600
};
$('#Grid').jqGrid(JQGridDefaults).navGrid('#GridPager', { view: false, del: false, add: false, edit: false, refresh: true },
{},
{},
{},
JQGridSearchDefaults);
$('#Grid').jqGrid('setGridWidth', $('#Grid').parents('.main-content').width() - 2);
$(window).resize(function () {
clearTimeout(this.id);
this.id = setTimeout(function () {
$('#Grid').jqGrid('setGridWidth', $('#Grid').parents('.main-content').width() - 2);
}, 300);
});
});
The sub grid icon appears correctly but when I click on the Expand icon an empty row appears (no headers and no ajax call is sent)
does anyone have an idea on why the ajax call is not happening?
Note: I also tried to use 'subgridtype' parameter and define to make the service call that too did not make the Ajax call.
subgridtype: function (rowidparam) {
$.ajax({
url: '/Items/Details',
cache: false,
type: 'Get',
dataType: "json",
data: { id: rowidparam.ItemID }
}).done(function (data) {
$('#Grid')[0].subGridJson(data, rowidparam.id);
});
},
subgridtype must be string, for you try json
subgridtype: 'json'

jqGrid edit row sends row number instead of id to web method

When I edit row and press Enter to send data to web method, it sends a row number instead of the id (eg. instead of id=111 it sends '3' which represents the 3rd row on the grid). How do I get the id value instead?
Here is code:
$(document).ready(function () {
var id;
var lastsel;
jQuery("#rowed3").jqGrid({
url:'Default3.aspx/GetData',
datatype: "xml",
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
ajaxRowOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
serializeRowData: function (postData) {
return JSON.stringify(postData);
},
mtype:'GET',
xmlReader: {
root: "programs",
row: "program",
repeatitems: false
},
colNames:['id','field1','field2'],
colModel:[
{ name: 'id', index: 'id', width: 55, hidden: false, editable: false, editrules: { edithidden: false }, hidedlg: true },
{ name: 'field1', index: 'field1', width: 90, editable: true },
{ name: 'field2', index: 'field2', width: 100, editable: true }
],
rowNum:10,
rowList:[10,20,30],
pager: '#prowed3',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
onSelectRow: function(id){
if(id && id!==lastsel){
jQuery('#rowed3').jqGrid('restoreRow',lastsel);
jQuery('#rowed3').jqGrid('editRow',id,true);
lastsel=id;
}
//$("#rowed3").jqGrid('setGridParam', { editurl: 'Default3.aspx/EditRow' });
},
onCellSelect: function(rowid,iCol,cellcontent,e) {
alert(cellcontent);},
//ondblClickRow: function(rowid) {
// jQuery('#rowed3').jqGrid('editRow',id,true);
//},
editurl: "Default3.aspx/EditRow",
caption: "Using events example"
});
jQuery("#rowed3").jqGrid('navGrid',"#prowed3",{edit:false,add:false,del:false});
});
[WebMethod]
//[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Xml)]
public static string EditRow(string id,string field1,string field2)
{
string x = id; ;
return x;
}
In colModel BOTH key:true and editable:true need to be set.
I didn't think editable of my hidden ID field was relevant, hence why original comment didn't just work

this.p is undefined jqgrid

I have an interesting issue. I have done this on multiple pages with multiple grids. The first grid works fine the second grid in this case fails to load. and give the following error:
this.p is undefined
...sArray(i)){P=true;h="last";U=f}else{i=[i];P=false}this.each(function(){var D=i.l... line 140 jquery.jqGrid.min.js
The user doble clicks on a row and that sets some variables and then calls the function locationGrid().
Like I said this has worked for me multiple times in the past, however on this page it fails. I have double checked and I am getting data back as shown below:
{"d":"{\"total\":1,\"page\":0,\"records\":1,\"rows\":[{\"invPartLocId\":1053,\"inventoryMasterId\":5,\"location\":null,\"itemType\":\"S\",\"currentQanity\":1,\"adjustedQauntity\":0,\"newLocationQty\":0,\"deptCode\":\"1401 \"}]}"}
Any help would be appreciated.
function locationGrid() {
$('#invLocAdjustGrid').jqgrid({
height: 290,
loadui: "block",
datatype: function (rdata) { getLocationData(rdata); },
colNames: ['invPartID', 'locationPartID', 'Loctaion', 'Type', 'Current QTY', 'Adjusted QTY', 'New Location QTY', 'Dept. Code'],
colModel: [
{ name: 'invPartLocId', width: 2, sortable: false, editable: false, hidden: true },
{ name: 'inventoryMasterId', width: 2, sortable: false, editable: false, hidden: true },
{ name: 'location', width: 250, editable: false, sortable: false },
{ name: 'itemType', width: 120, editable: false, sortable: false, align: 'center' },
{ name: 'currentQanity', width: 50, editable: false, sortable: false },
{ name: 'adjustedQauntity', width: 50, editable: false, sortable: false },
{ name: 'newLocationQty ', width: 50, editable: false, sortable: false },
{ name: 'deptCode', width: 50, editable: false, sortable: false }
],
pager: jQuery('#rptCodesPager'),
viewrecords: true,
width: 890,
gridComplete: function () {
$('#load_invLocAdjustGrid').hide();
$(this).prop('p').loadui = 'enable';
$('#lui_invLocAdjustGrid').hide();
},
afterInsertRow: function (rowid, aData) {
},
ondblClickRow: function (rowid) {
var myID = $('#invLocAdjustGrid').getCell(rowid, 'invPartLocId');
Ldclicked(myID);
}
});
}
function getLocationData(rdata) {
var theID = tempID;
tempID = "";
var myDTO = { 'id': theID };
var toPass = JSON.stringify(myDTO);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "INV_Inventory_Adjustment.aspx/getInventoryLocationById",
data: toPass,
success: function (data, textStatus) {
if (textStatus == "success")
ReceivedLocationData(JSON.parse(getMain(data)).rows);
},
error: function (data, textStatus) { alert('An error has occured retrieving data!'); }
});
}
function ReceivedLocationData(data) {
var thegrid = $('#invLocAdjustGrid');
var isGood = data.length;
for (var i = 0; i < isGood; i++) {
thegrid.addRowData(i + 1, data[i]);
}
}
Sorry, but your code is buggy. Moreover I recommend you to rewrite the whole code and I try to explain why.
The first important error is that you use $('#invLocAdjustGrid').jqgrid({...}); in the locationGrid instead of $('#invLocAdjustGrid').jqGrid({...});. JavaScript is case sensitive, so it's very important to use jqGrid instead of jqgrid.
Next problem exist because you use some variables and functions tempID, Ldclicked and getMain which you not defined in the posted code.
After making minimal changes the demo works. I commented only "POST" to use HTTP GET because I get the JSON directly from the file and have no active components on the wed server.
One more problem which you clear have is that your server code serialize the results twice. Typically one have the problem because of wrong usage of ASMX WebMethods. One should not convert the object to JSON manually. Instead of that one need just return the object itself. Because of the problem the d property of the JSON are not the object itself and is a string which should be one more time be parsed:
{
"d": "{\"total\":1,\"page\":0,\"records\":1,\"rows\":[{\"invPartLocId\":1053,\"inventoryMasterId\":5,\"location\":null,\"itemType\":\"S\",\"currentQanity\":1,\"adjustedQauntity\":0,\"newLocationQty\":0,\"deptCode\":\"1401 \"}]}"
}
Even such wrong formatted data can be read by jqGrid without usage datatype as function. Moreover you should always use gridview: true and never use afterInsertRow and almost never use addRowData. The modified code can be about the following:
var tempID = "abc";
$('#invLocAdjustGrid').jqGrid({
url: "INV_Inventory_Adjustment.aspx/getInventoryLocationById",
mtype: "POST",
datatype: "json",
postData: {
id: function () { return tempID; } // ??? I don't know which data should be send
},
ajaxGridOptions: { contentType: "application/json" },
serializeRowData: function (data) {
return JSON.stringify(data);
},
beforeProcessing: function (data) {
$.extend (true, data, $.parseJSON(data.d));
},
jsonReader: {repeatitems: false},
loadonce: true,
colNames: ['invPartID', 'locationPartID', 'Loctaion', 'Type', 'Current QTY', 'Adjusted QTY', 'New Location QTY', 'Dept. Code'],
colModel: [
{ name: 'invPartLocId', width: 2, key: true, hidden: true },
{ name: 'inventoryMasterId', width: 2, hidden: true },
{ name: 'location', width: 250 },
{ name: 'itemType', width: 120, align: 'center' },
{ name: 'currentQanity' },
{ name: 'adjustedQauntity' },
{ name: 'newLocationQty ' },
{ name: 'deptCode' }
],
cmTemplate: {sortable: false, width: 50},
pager: '#rptCodesPager',
viewrecords: true,
gridview: true,
loadui: "block",
height: 290,
width: 890,
ondblClickRow: function (rowid) {
//Ldclicked(rowid);
}
});
The next demo demonstrate that the code work. I included in the demo the option loadonce: true which can be helpful for you too.

jqgrid apply filter after reload?

Am using jqgrid, loading data once, sorting and filtering locally and doing a refresh after each update/insert/delete. It works fine, besides that if I am using a filter (on top of grid), the filter remains the same after refresh, but the filter is not re-applied on the newly loaded data.
I have tried to call mygrid[0].triggerToolbar() after reloading grid with trigger('reloadGrid'), but there is no effect.
Thanks for any help or pointers :-)
Code below:
var lastsel;
var mygrid;
var currentLang;
//setup grid with columns, properties, events
function initGrid(lang, productData, resellerData, resellerSearchData) {
mygrid = jQuery("#list2").jqGrid({
//data loading settings
url: '/public/Gadgets/LinkGadget/ProductLinks/' + lang,
editurl: "/public/Gadgets/LinkGadget/Edit/" + lang,
datatype: "json",
mtype: 'POST',
jsonReader: {
root: "rows",
cell: "",
page: "currpage",
//total: "totalrecords",
repeatitems: false
},
loadError: function (xhr, status, error) { alert(status + " " + error); },
//column definitions
colNames: ['Id', 'ProductId', 'Reseller Name', 'Link', 'Link Status'],
colModel: [
{ name: 'Id', index: 'Id', width: 40, sortable: false, resizable: true, editable: false, search: false, key: true, editrules: { edithidden: true }, hidden: true },
{ name: 'ProductId', index: 'ProductId', width: 190, sortable: true, sorttype: 'text', resizable: true, editable: true, search: true, stype: 'select', edittype: "select", editoptions: { value: productData }, editrules: { required: true} },
{ name: 'ResellerName', indexme: 'ResellerName', width: 190, sortable: false, sorttype: 'text', resizable: true, editable: true, search: true, stype: 'select', edittype: "select", editoptions: { value: resellerData }, editrules: { required: true }, searchoptions: { sopt: ['eq'], value: resellerSearchData} },
{ name: 'Link', index: 'Link', width: 320, sortable: true, sorttype: 'text', resizable: true, editable: true, search: true, edittype: "textarea", editoptions: { rows: "3", cols: "50" }, editrules: { required: true }, searchoptions: { sopt: ['cn']} },
{ name: 'LinkStatus', index: 'LinkStatus', width: 100, sortable: false, resizable: true, editable: false, search: false, formatter: linkStatusFormatter}],
//grid settings
//rowList: [10, 25, 50],
rowNum: 20,
pager: '#pager2',
sortname: 'ProductId',
sortorder: 'asc',
height: '100%',
viewrecords: true,
gridview: true,
loadonce: true,
viewsortcols: [false, 'vertical', true],
caption: " Product links ",
//grid events
onSelectRow: function (id) {
if (id && id !== lastsel) {
if (lastsel == "newid") {
jQuery('#list2').jqGrid('delRowData', lastsel, true);
}
else {
jQuery('#list2').jqGrid('restoreRow', lastsel);
}
jQuery('#list2').jqGrid('editRow', id, true, null, afterSave); //reload on success
lastsel = id;
}
},
gridComplete: function () {
//$("#list2").setGridParam({ datatype: 'local', page: 1 });
$("#pager2 .ui-pg-selbox").val(25); //changing the selected values triggers paging to work for some reason
}
});
//page settings
jQuery("#list2").jqGrid('navGrid', '#pager2',
{ del: false, refresh: false, search: false, add: false, edit: false }
);
//refresh grid button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Refresh", title: "Refresh grid", buttonicon: 'ui-icon-refresh',
onClickButton: function () {
reload();
}
});
//clear search button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Clear search", title: "Clear Search", buttonicon: 'ui-icon-refresh',
onClickButton: function () {
mygrid[0].clearToolbar();
}
});
//add row button
jQuery("#list2").jqGrid('navButtonAdd', '#pager2', { caption: "New", buttonicon: 'ui-icon-circle-plus',
onClickButton: function (id) {
var datarow = { Id: "newid", ProductId: "", ResellerName: "", Link: "" };
jQuery('#list2').jqGrid('restoreRow', lastsel); //if editing other row, cancel this
lastsel = "newid"; // id;
var su = jQuery("#list2").addRowData(lastsel, datarow, "first");
if (su) {
jQuery('#list2').jqGrid('editRow', lastsel, true, null, afterSave); //reload on success
jQuery("#list2").setSelection(lastsel, true);
}
},
title: "New row"
});
//delete row button
jQuery("#list2").jqGrid('navButtonAdd', "#pager2", { caption: "Delete", title: "Delete row", buttonicon: 'ui-icon-circle-minus',
onClickButton: function () {
if (lastsel) {
if (confirm('Are you sure you want to delete this row?')) {
var url = '/public/Gadgets/LinkGadget/Edit/' + currentLang;
var data = { oper: 'del', id: lastsel };
$.post(url, data, function (data, textStatus, XMLHttpRequest) {
reload();
});
lastsel = null;
}
else {
jQuery("#list2").resetSelection();
}
}
else {
alert("No row selected to delete.");
}
}
});
jQuery("#list2").jqGrid('filterToolbar');
}
//Used by initGrid - formats link status column by adding button
function linkStatusFormatter(cellvalue, options, rowObject) {
if (rowObject.Id != "newrow")
return "<input style='height:22px;width:90px;' type='button' " + "value='Check link' " + "onclick=\"CheckLink(this, '" + rowObject.Id + "'); \" />";
else
return "";
}
//Used by initGrid - reloads grid
function reload() {
//jqgrid setting "loadonce: true" will reset datatype from json to local after grid has loaded. "datatype: local"
// does not allow server reloads, therefore datatype is reset before trying to reload grid
$("#list2").setGridParam({ datatype: 'json' }).trigger('reloadGrid');
//mygrid[0].clearToolbar();
lastsel = null;
//Comments: after reload, toolbar filter is not applied to refreshed data. Tried row below without luck
//mygrid[0].triggerToolbar();
}
//after successful save, reload grid and deselect row
function afterSave() {
reload();
}
Your data is not getting re binded to the grid after save/update delete

Resources