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

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

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.

on jquery ajax call , unable to bind jqgrid data

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");
});
});

How to save/restore the CheckBox state in jqGrid across webMethod?

I am using jqGrid with "multiselect: true" and webMethods. I need to persist state, so I am going to put the Grid state in the DB, in order to do this I need to know which rows have selected checkboxes and pass that through the webMethod, then on the other side I need to be able to specify to the Grid to select or unselect a particular checkbox.
This is my current binding code, serializeGridData doesn't pick up the checkbox state.
$(document).ready(function () {
jQuery("#selectedInmateList").jqGrid({
url: "<%= AdminPath %>WebMethods/WebService1.asmx/GetUsersJSON3",
postData: {
inmateList: function () {
return InmateListArg;
}
},
mtype: 'POST',
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
var propertyName, propertyValue, dataToSend = {};
for (propertyName in postData) {
if (postData.hasOwnProperty(propertyName)) {
propertyValue = postData[propertyName];
if ($.isFunction(propertyValue)) {
dataToSend[propertyName] = propertyValue();
} else {
dataToSend[propertyName] = propertyValue
}
}
}
return JSON.stringify(dataToSend);
},
onSelectRow: function (id) {
},
jsonReader: {
root: "d.rows",
page: "d.page",
total: "d.total",
records: "d.records"
},
colNames: ['select', 'LastName', 'FirstName', 'id'],
colModel: [
{ name: 'select', index: 'select', width: 300, align: 'center' },
{ name: 'LastName', index: 'LastName', width: 300, align: 'center' },
{ name: 'FirstName', index: 'FirstName', width: 300, align: 'center' },
{ name: 'id', index: 'id', align: 'center', hidden: true }
],
pager: '#prod_pager',
rowList: [10, 20, 30],
sortname: 'Code',
sortorder: 'desc',
rowNum: 10,
loadtext: "Loading....",
shrinkToFit: false,
multiselect: true,
emptyrecords: "No records to view",
//width: x - 40,
height: "auto",
rownumbers: true,
//subGrid: true,
caption: 'Selected Inmates'
});
});
If I understand your correctly you need first of all to send the current list of selected rows to the server. For example if the user select or unselect new row you can send the current list of the rows directly to the server. You can do this inside of onSelectRow and onSelectAll callbacks. Additionally you need that the server send you back only the data of the current page (the full data if you use loadonce: true option), but the list of ids of the rows which need be selected too. Inside of loadComplete you can call in the loop setSelection method to select the rows.
I would recommend you to examine the code of the callback onSelectRow, onSelectAll and loadComplete of the demo created for the answer. The old answer provide the basis of the same idea.
To pass the selected row IDs into the webMethod I used this:
var selectedIDs = jQuery('#selectedInmateList').jqGrid('getGridParam', 'selarrrow');
Then I added that to my webMethod param 'InmateListArg'
Then I added a hidden column which indicated if the row should be checked or not, then I used the loadComplete event to select the desired row based on the data in the hidden column.
$(document).ready(function () {
jQuery("#selectedInmateList").jqGrid({
url: "<%= AdminPath %>WebMethods/WebService1.asmx/GetUsersJSON3",
postData: {
inmateList: function () {
return InmateListArg;
}
},
mtype: 'POST',
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
var propertyName, propertyValue, dataToSend = {};
for (propertyName in postData) {
if (postData.hasOwnProperty(propertyName)) {
propertyValue = postData[propertyName];
if ($.isFunction(propertyValue)) {
dataToSend[propertyName] = propertyValue();
} else {
dataToSend[propertyName] = propertyValue
}
}
}
return JSON.stringify(dataToSend);
},
onSelectRow: function (id) {
},
loadComplete: function (id) {
idsOfSelectedRows = [];
var gridData = jQuery("#selectedInmateList").getRowData();
for (i = 0; i < gridData.length; i++) {
var isChecked = gridData[i]['checked'];
var id = gridData[i]['id'];
if (isChecked == 'True') {
idsOfSelectedRows.push(id);
}
}
var $this = $(this), i, count;
for (i = 0, count = idsOfSelectedRows.length; i < count; i++) {
$this.jqGrid('setSelection', idsOfSelectedRows[i], false);
}
},
jsonReader: {
root: "d.rows",
page: "d.page",
total: "d.total",
records: "d.records"
},
colNames: ['select', 'LastName', 'FirstName', 'id', 'checked'],
colModel: [
{ name: 'select', index: 'select', width: 300, align: 'center' },
{ name: 'LastName', index: 'LastName', width: 300, align: 'center' },
{ name: 'FirstName', index: 'FirstName', width: 300, align: 'center' },
{ name: 'id', index: 'id', align: 'center' /*, hidden: true*/ },
{ name: 'checked', index: 'checked', align: 'center' }
],
pager: '#prod_pager',
rowList: [10, 20, 30],
sortname: 'Code',
sortorder: 'desc',
rowNum: 10,
loadtext: "Loading....",
shrinkToFit: false,
multiselect: true,
emptyrecords: "No records to view",
//width: x - 40,
height: "auto",
rownumbers: true,
//subGrid: true,
caption: 'Selected Inmates'
});
jQuery("#prodgrid").jqGrid('navGrid', '#prod_pager',
{ edit: false, add: false, del: true, excel: true, search: false });
});

how to use jqgrid extraParam parameter of saveRow

where in one cell edittype is select with key value pair like below.
colModel: [
{name: 'Code', index: 'Code', width: '16%', editable: true, sortable: true },
{ name: 'ABC', index: 'ABC', width: '16%', editable: true, edittype: "select", editoptions: { value: "FE:FedEx;TN:TNT"} },
{ name: 'Emailid', index: 'Emailid', width: '16%', editable: true, sortable: true },
],
Now while adding new row if i selected the FedEx for ABC column it will send the FE to EditURL Link not FedEX so i want to send the FEDEX using extraParam to EditURL.
So please anyone let me know how to implement it.
For this my code is below
UPDATED CODE
var grid = jQuery("#list5").jqGrid({
url: '/home1/GetUserData',
datatype: "json",
mtype: "POST",
colNames: ['Code', 'LoginID', 'Emailid'],
colModel: [
{name: 'Code', index: 'Code', width: '16%', editable: true, sortable: true },
{ name: 'LoginID', index: 'LoginID', width: '16%', editable: true, sortable: true },
{ name: 'Emailid', index: 'Emailid', width: '16%', editable: true, edittype: "select", editoptions: { value: "FE:FedEx;TN:TNT"} },
],
rowNum: 10,
autowidth: true,
height: '100%',
rowList: 10,
pager: $("#pager2"),
editurl: "/home1/EditUserData",
onSelectRow: function (id) {
if (id && id !== lastsel2) {
if (id == "new_row") {
grid.setGridParam({ editurl: "/home1/InsertUserData" });
}
else {
grid.setGridParam({ editurl: "/home1/EditUserData" });
}
jQuery('#list5').restoreRow(lastsel2);
jQuery('#list5').jqGrid('editRow', id, true, pickdates);
$("#list5_ilsave").addClass("ui-state-disabled");
$("#list5_ilcancel").addClass("ui-state-disabled");
$("#list5_iladd").removeClass("ui-state-disabled");
$("#list5_iledit").removeClass("ui-state-disabled");
lastsel2 = id;
}
},
caption: "Simple data manipulation"
});
jQuery("#list5").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {}, { url: '/home1/DeleteUserData' });
jQuery('#list5').jqGrid('inlineNav', '#pager2', { edit: true, add: true, editParams: {extraparam: XYZ()}});
});
function XYZ()
{
// from here i want to return the text of combo of selected row.
}
Update code of Oleg
var grid = jQuery("#list5"),
editingRowId,
myEditParam = {
keys: true,
oneditfunc: function (id) {
editingRowId = id;
},
afterrestorefunc: function (id) {
editingRowId = undefined;
},
extraparam:
// we get the text of selected option from the column
// 'Emailid' and include the data as additional
// parameter 'EmailidText'
// EmailidText: function () {
// return $("#" + editingRowId + "_Emailid>option:selected").text();
//}
// **my changes here bind ABC Function which return key , value pair of object** IS THIS POSSIBLE
function () {
ABC();
}
};
grid.jqGrid({
url: '/home1/GetUserData',
datatype: "json",
...
onSelectRow: function (id) {
var $this = $(this), gridIdSelector = '#' + $.jgrid.jqID(this.id);
$this.jqGrid('setGridParam', {
editurl: (id === "new_row" ?
"/home1/InsertUserData" :
"/home1/EditUserData")
});
if (editingRowId !== id) {
$(gridIdSelector + "_iledit").click();
}
}
});
$grid.jqGrid('navGrid', '#pager',
{ edit: false, add: false, search: false, refresh: false},
{}, {}, { url: '/home1/DeleteUserData' });
// inlineNav has restoreAfterSelect: true per default so we don't need to call
// restoreRow explicitly
$grid.jqGrid('inlineNav', '#pager',
{ edit: true, add: true, editParams: myEditParam,
addParams: {addRowParams: myEditParam } });
The code could be about the following
var grid = jQuery("#list5"),
editingRowId,
myEditParam = {
keys: true,
oneditfunc: function (id) {
editingRowId = id;
},
afterrestorefunc: function (id) {
editingRowId = undefined;
},
extraparam: {
// we get the text of selected option from the column
// 'Emailid' and include the data as additional
// parameter 'EmailidText'
EmailidText: function () {
return $("#" + editingRowId + "_Emailid>option:selected").text();
}
}
};
grid.jqGrid({
url: '/home1/GetUserData',
datatype: "json",
...
onSelectRow: function (id) {
var $this = $(this), gridIdSelector = '#' + $.jgrid.jqID(this.id);
$this.jqGrid('setGridParam', {
editurl: (id === "new_row" ?
"/home1/InsertUserData" :
"/home1/EditUserData")
});
if (editingRowId !== id) {
$(gridIdSelector + "_iledit").click();
}
}
});
$grid.jqGrid('navGrid', '#pager',
{ edit: false, add: false, search: false, refresh: false},
{}, {}, { url: '/home1/DeleteUserData' });
// inlineNav has restoreAfterSelect: true per default so we don't need to call
// restoreRow explicitly
$grid.jqGrid('inlineNav', '#pager',
{ edit: true, add: true, editParams: myEditParam,
addParams: {addRowParams: myEditParam } });

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