How to set Total Pages in JQGrid if I'm using server side paging? - jqgrid

I'm new to JQGrid and learning the paging currently. I'm trying to implement server side paging.
Consider I have 45 records. Since, Server side returns the requested records of a specified page based on page size(say 10), my pager changes to 1 immediately after clicking next button. I'm not able to move on to further pages since the total page is 1 now. Total page is automatically getting calculated based on the records present. So how to manage the total pages value in this case?
$("#jqGridOutbox").jqGrid({
datatype: 'json',
mtype: 'POST',
colNames: ['Title', 'Submitted By', 'Assigned To', 'Submitted On', 'History', 'WorkFlow Name'],
colModel: [
{ name: 'TitleOut', index: 'Title', width: 173, sortable: true, search: true, formatter: ShowItemFormatterOutbox },
{ name: 'CreatedByOut', index: 'CreatedBy', width: 173, sortable: true, searchoptions: {} },
{ name: 'PendingOnOut', index: 'PendingOn', width: 173, sortable: true, searchoptions: {} },
{ name: 'CreatedOnOut', index: 'CreatedOn', width: 173, sortable: true, searchoptions: {} },
{ name: 'HistoryOut', index: 'History', width: 80, sortable: false, search: false, formatter: ViewHistoryFormatter },
{ name: 'WorkFlowNameOut', index: 'WorkFlowName', width: 170, sortable: true, search: true }
],
datatype: function (postData) { getDataOutBox(postData, OutMode, OutPageNumber); },
ajaxGridOptions: { contentType: "application/json" },
loadonce: 'false',
viewrecords: 'true',
width: 987,
viewsortcols: [true, 'vertical', true],
height: 250,
rowList: [2, 5, 10, 20, 30, 100],
hidegrid: 'false',
rowNum: 2,
autowidth: true,
gridview: true,
shrinkToFit: false,
showQuery: 'true',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id: "Title",
userdata: "userdata",
repeatitems: true
},
gridComplete: function () {
$("#load_jqGridOutbox").hide();
$("tr.jqgrow:odd").css("background", "white");
$("tr.jqgrow:even").css("background", "#f7f7f7");
},
pager: '#jqGridOutboxPager',
pagerpos: 'center'
});
The function mapped to datatype is GetDataOutBox()
function getDataOutBox(pdata, mode, pageNumber) {
var params = new Object();
params.page = pdata.page;
params.pageSize = pdata.rows;
params.sortIndex = pdata.sidx;
params.sortDirection = pdata.sord;
params.Title = $("#gs_TitleOut").val() == undefined ? '' : $("#gs_TitleOut").val();
params.CreatedBy = $("#gs_CreatedByOut").val() == undefined ? '' : $("#gs_CreatedByOut").val();
params.PendingOn = $("#gs_PendingOnOut").val() == undefined ? '' : $("#gs_PendingOnOut").val();
params.CreatedOn = $("#gs_CreatedOnOut").val() == undefined ? '' : $("#gs_CreatedOnOut").val();
params.WorkFlowName = $("#gs_WorkFlowNameOut").val() == undefined ? '' : $("#gs_WorkFlowNameOut").val();
params.mode = mode;
params.pageNumber = pageNumber;
$("#load_jqGridOutbox").show();
$.ajax({
url: 'ClaySysWorkFlowDashBoard.aspx/GetOutboxData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
dataType: "json",
success: function (data, st) {
if (st == "success") {
var grid = $("#jqGridOutbox")[0];
grid.addJSONData(data.d);
//$("#jqGridOutbox")[0].updatepager(false, true);
}
},
error: function () {
alert("An error has occured retrieving the data!");
}
});
}
The model which gets returned is
public class JQGrid
{
public class Row
{
public int id { get; set; }
public List<string> cell { get; set; }
public Row()
{
cell = new List<string>();
}
}
public int page { get; set; }
public int total { get; set; }
public int records { get; set; }
public List<Row> rows { get; set; }
public JQGrid()
{
rows = new List<Row>();
}
}
Based on the page number, I select only the respective set of 10 records. Thus after returning that, the total pages changes to 1.

Related

On First load of jqgrid how to load page of specific record?

Using Jquery.Jqgrid v4.4.4
I have 10 pages in my State grid, i want to display the page which holds state name 'Tamilnadu' on first of the jqgrid loads. Not to bring the state on the first page, need to display that page on the first time.
EDIT: My Jqgrid code, here i have 'State' column contains 10+ pages , in one of the page 'Tamilnadu' state record is there. Please help me on how to load the grid with that page on first load.
// Setting up County Grid properties
$(function () {
$("#CountyGrid").jqGrid({
url: '/ControlTables/GetCountyResult',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'Get',
colNames: ['CountyIdentifier', 'Active', 'State', 'County', 'County Number', AddNewBtn],
colModel: [
{
Key: true, name: 'CountyIdentifier', index: 'CountyIdentifier', width: 16, editable: false, sortable: true, align: "left", classes: "grid-col",
hidden: true, displayName: "CountyIdentifier"
},
{
name: 'ActiveFlag', index: 'ActiveFlag', width: 4, align: 'center', editable: true,
edittype: 'checkbox', editoptions: { value: "True:False", defaultValue: "True" }, formatter: "checkbox", displayName: "Active"
},
{
name: 'StateIdentifier', index: 'StateIdentifier', editable: true, formatter: 'select', sortable: true,
edittype: 'select', width: 19, align: "left", classes: "grid-col", editoptions: { style: "height:23px;" }, displayName: "State", valueField: "StateText",
},
{
name: 'CountyText', index: 'CountyText', width: 19, editable: true, sortable: true, align: "left", classes: "grid-col",
editoptions: { style: "height:23px;", maxlength: "48", dataInit: function (el) { $(el).css('text-transform', 'uppercase'); } }, displayName: "County"
},
{
name: 'CountyNumber', index: 'CountyNumber', width: 7, editable: true, sortable: true, align: "left", classes: "grid-col",
editoptions: { style: "height:23px;", maxlength: "5" }, displayName: "County Number"
},
{
name: "action", index: "action", sortable: false, editable: false, align: "center", width: "7", displayName: "Action"
},
],
// Call select row function
onSelectRow: function (id) {
if (onPagingLastSel) {
$('#CountyGrid').jqGrid('resetSelection', lastsel, true);
onPagingLastSel = false;
}
rowSelect(id);
},
onPaging: function () {
//Prompt to save pending changes when the user try to navigate Next/Previous/Front/Last page.
if (lastsel != null) {
$('#CountyGrid').jqGrid('saveRow', lastsel, {});
var editrowData = jQuery("#CountyGrid").getRowData(lastsel);
var editRow_ActiveFlag = editrowData['ActiveFlag']
var editRow_StateIdentifier = editrowData['StateIdentifier']
var editRow_CountyText = editrowData['CountyText']
var editRow_CountyNumber = editrowData['CountyNumber']
$('#CountyGrid').jqGrid('editRow', lastsel, {});
if ((lastsel_StateIdentifier != editRow_StateIdentifier && editRow_StateIdentifier != undefined)||
(lastsel_CountyText != editRow_CountyText && editRow_CountyText != undefined) ||
(lastsel_CountyNumber != editRow_CountyNumber && editRow_CountyNumber != undefined) ||
(lastsel_ActiveFlag != editRow_ActiveFlag && editRow_ActiveFlag != undefined)) {
DialogConfirmSave("GENL-002");
onPagingLastSel = true;
return 'stop';
}
else {
lastsel = null;
//enable New Button
$("#NewBtnId").removeClass('add-new-button-disable');
$("#NewBtnId").removeAttr("disabled");
}
}
},
// load all States into jqGrid dropdown
beforeProcessing: function (response) {
var $self = $(this),
options = response.colModelOptions, StateIdentifier;
if (options != null) {
for (StateIdentifier in options) {
if (options.hasOwnProperty(StateIdentifier)) {
$("#CountyGrid").jqGrid("setColProp", StateIdentifier, options[StateIdentifier]);
}
}
}
},
// Grid column header alignment to the left diable new button for general users
loadComplete: function () {
$("#CountyGrid").jqGrid("setLabel", "Active", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "StateIdentifier", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "CountyText", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "CountyNumber", "", { "text-align": "left" })
},
pager: jQuery('#CountyPager'),
rowNum: jqGridRowCount,
rowList: GridRowList,
viewrecords: true,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
multiselect: false,
autowidth: true,
height: 560,
hidegrid: false,
}).navGrid('#CountyPager', {
edit: false, add: false, del: false, search: false, refresh: false, reload: false, restoreAfterSelect: false
})
});
My Controller code:
public JsonResult GetCountyResult(string sidx, string sord, int page, int rows, bool getAllRecords = false)
{
objCountyViewModel = new CountyViewModel();
int totalRecords = 0;
if (Session["CountyList"] != null && Session["CountyList"] is List<CountyModel>)
{
objCountyViewModel.CountyModelList = (List<CountyModel>)Session["CountyList"];
if (objCountyViewModel.CountyModelList != null)
{
Session["CountyList"] = objCountyViewModel.SortCounty(sidx, sord);
totalRecords = objCountyViewModel.CountyModelList.Count();
}
}
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
rows = getAllRecords ? totalRecords : rows;
var jsonData = new
{
colModelOptions = new
{
StateIdentifier = new
{
formatter = "select",
edittype = "select",
editoptions = new
{
value = objCountyViewModel.GetStateDropdownList()
}
}
},
total = totalPages,
page,
records = totalRecords,
rows = objCountyViewModel.GetCountyPageList(page, rows)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}

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

JQGrid Sorting is not working - MVC3

I am trying to sort the each columns in my JQGrid but its not working. Please refer my code below and help me
//View Code
$("#JQGridID").jqGrid({
url: '/Control/ActionResult/',
datatype: 'json',
mtype: 'POST',
colNames: ['Number', 'Unit'],
colModel: [
{ name: 'NNumber', index: 'Number', align: 'left', sortable: true, sorttype: 'int' },
{ name: 'NUnit', index: 'Unit', align: 'Center', sortable: true }
], pager: jQuery('#pager'),
cmTemplate: { title: false },
width: widthValue - 15,
height: 435,
rowNum: 20,
rowList: [20, 30, 40, 50, 60],
viewrecords: true,
gridComplete: loadCompleteFunction,
altRows: true,
sortorder: 'desc',
sortname: 'Number',
sortable: true,
onSortCol: function (index, idxcol, sortorder) {
if (this.p.lastsort >= 0 && this.p.lastsort !== idxcol
&& this.p.colModel[this.p.lastsort].sortable !== false) {
$(this.grid.headers[this.p.lastsort].el).find(">div.ui-jqgrid-sortable>span.s-ico").show();
}
}
,
onSelectRow: showMessageDetails,
postData: {
},
loadError: function (xml) { alert('Unable to load result data.'); }
});
//Control code
[HttpPost]
public ActionResult GetSearchPositionResult(string sidx, string sord, int page, int rows)
{
_Object = new PositionModel();
_Object.CurrentPage = page;
_Object.PageRowCount = rows;
_Object.load();
var result = new
{
total = _Object.TotalPages,
page = page,
sort = sidx,
sord = sord,
records = _Object.TotalRows,
rows = _ObjectPM.SearchResult.Select(p => new
{
cell = new string[]{
p.Number,
p.Unit
},sidx
}).OrderBy(a => a.sidx).ToArray(), };
return Json(result, JsonRequestBehavior.AllowGet);
}
In case of datatype: 'json' the sorting of data (sortable: true in colModel) is not handled on client-side by jqGrid but it has to be handled on server-side by your code. In another words you need to sort your _Object.SearchResult by the column name which you will receive in sidx parameter (the sorting direction is passed in sord parameter).
Here you can find a sample project which can help with using jqGrid in ASP.NET MVC: jqGrid in ASP.NET MVC 3 and Razor

jqgrid with web api not getting populated

I am very new to jqGrid. I am trying to load simple jqgrid using asp.net web api.
The api send back the list of emailDto. The emailDto is plain class with 3 public properties
The problem is the jqgrid is not getting populated. Any help is very much appreciated.
function dataBindToGrid() {
var lastsel;
$("#emailgrid").jqGrid({
url: '/api/email/',
datatype: "json",
mytype: 'GET',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
colNames: ['Address ID', 'Type', 'Email'],
colModel: [{ name: 'Address_ID', width: 70, primaryKey: true, editable: false, sortable: false, hidden: false, align: 'left' },
{ name: 'Email_Type', width: 70, editable: true, align: 'left', sortable: false },
{ name: 'Email_Address', width: 200, editable: true, align: 'left', sortable: false }
],
onSelectRow: function (id) {
if (id && id !== lastsel) {
var grid = $("#emailgrid");
grid.restoreRow(lastsel);
grid.editRow(id, true);
lastsel = id;
}
},
//This event fires after all the data is loaded into the grid
gridComplete: function () {
//Get ids for all current rows
var dataIds = $('#emailgrid').jqGrid('getDataIDs');
for (var i = 0; i < dataIds.length; i++) {
//Put row in edit state
$("#emailgrid").jqGrid('editRow', dataIds[i], false);
}
},
rowNum: 3,
viewrecords: true,
caption: "Email Addresses"
});
}
When configured for jsondatatype, jqGrid expects data in the following json format:
{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
{"id" :"2", "cell":["cell21", "cell22", "cell23"]},
...
]
}
data returned must match this otherwise it will not work. This is the default json structure (you can change this if you want). Depending on what browser you are using, you should be able to see the ajax request and response with what data is being sent and returned when the grid is building itself (Firefox use firebug, IE use the developer toolbar)
as per here
Solved!
Just added to jqGrid below and it works.
jsonReader: {
repeatitems: false,
page: function () { return 1; },
root: function (obj) { return obj; },
records: function (obj) { return obj.length; }
},

jqGrid Problem Binding Subgrid

I have a jqGrid that is not correctly displaying the subgrid rows. When I load the page, the regular grid rows display fine as well as the plus sign next to each of them, but when I click the plus button to expand them, the "Loading..." message just remains and nothing happens. I don't know if it makes a difference, but I am trying to do it on client side (loadonce: true).
Here is the code for creating the grid:
$("#Grid1").jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: null,
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
datatype: function(postdata) {
$(".loading").show(); // make sure we can see loader text
$.ajax({
url: 'WebServices/GetJSONData.asmx/getGridData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function(data, st) {
if (st == "success") {
var grid = $("#Grid1")[0];
grid.addJSONData(JSON.parse(data.d));
//Loadonce doesn't work, have to do its dirty work
$('#Grid1').jqGrid('setGridParam', { datatype: 'local' });
//After rows are loaded, have to manually load subgrid rows
var subgridData = JSON.parse(data.d).subgrid;
var lista = jQuery("#Grid1").getDataIDs();
var rowData;
//Iterate over each row in grid
for (i = 0; i < lista.length; i++) {
//Get current row data
rowData = jQuery("#Grid1").getRowData(lista[i]);
}
}
},
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
},
coNames: ['Inv No', 'Amount', 'Store', 'Notes'],
colModel: [
{ name: 'InvNum', index: 'InvNum', width: 200 },
{ name: 'Amount', index: 'Amount', width: 55 },
{ name: 'Store', index: 'Store', width: 50 },
{ name: 'Notes', index: 'Notes', width: 100 }
],
subGrid: true,
subGridModel: [{
name: ['InvNum', 'Name', 'Qauntity'],
width: [55, 200, 80],
params: ['InvNum']
}],
rowNum: 10,
rowList: [10, 20, 50],
pager: '#Div1',
viewrecords: true,
width: 500,
height: 230,
scrollOffset: 0,
loadonce: true,
ignoreCase: true,
gridComplete: function() {
$(".loading").hide();
}
}).jqGrid('navGrid', '#Div1', { del: false, add: false, edit: false }, {}, {}, {}, { multipleSearch: true });
Here the code that I am using in the webservice call to create the JSON data:
IEnumerable orders = getOrders();
IEnumerable items = getItems();
int k = 0;
var jsonData = new
{
totalpages = totalPages, //--- number of pages
page = pageIndex, //--- current page
totalrecords = totalRecords, //--- total items
rows = (
from row in orders
select new
{
id = k++,
cell = new string[] {
row.InvNum.ToString(), row.Amount.ToString(), row.Store, row.Notes
}
}
).ToArray(),
subgrid = (
from row in items
select new
{
cell = new string[] {
row.InvNum.ToString(), row.Name, row.Quantity.ToString()
}
}
).ToArray()
};
result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);

Resources