Append Data to jqGrid - javascript

I'd like to append data to jqgrid so when the user hits See more button, it loads additional data retrieved via JSON request.
Html
<div id="SeeMoreSearchResultsDiv" class="scroll" style="text-align: center;">
<div id="ancSearchResultsSeeMore" class="grayButton" style="float: left; left: 350px;"> <ul>
<li class="ltImg"></li>
<li>See more</li>
<li class="rtImg"></li>
</ul> </div>
</div>
Here's my Grid
jQuery("#SearchResultDataGrid").jqGrid({
url: updatedURL,
datatype: "json",
ajaxGridOptions: { contentType: "application/json" },
jsonReader: {
id: "CTSID",
cell: "",
root: function (obj) { return obj.Results; },
page: function () { return 1; },
total: function (obj) { return obj.Count; },
records: function (obj) { return obj.length; },
repeatitems: false
},
colNames: ['CTS ID', 'Name', 'City', 'Type', 'Status', 'Platinum ID', 'RSM Group Code'],
colModel: [{ name: 'CTSID', index: 'CTSID', width: 40, align: "center" },{ name: 'CustomerName', index: 'CustomerName', width: 150, align: "center" }, { name: 'CityAndState', index: 'CityAndState', width: 90, align: "center" }, { name: 'CustomerTypeName', index: 'CustomerTypeName', width: 50, align: "center" }, { name: 'CustomerStatusName', index: 'CustomerStatusName', width: 50, align: "center" }, { name: 'PlatinumID', index: 'PlatinumID', width: 50, align: "center" },{ name: 'RSMGroupCode', index: 'RSMGroupCode', width: 100, align: "center" }],
pager: false,
rowNum: -1,
// rowList:[25,50,75,100],
sortorder: "asc",
autowidth: true,
viewrecords: true,
shrinkToFit: true,
rownumbers: false,
clearGridriData: false,
gridview: true,
caption: false});
and here's how I'm calling it
function seeMoreFunction() {
page = page + 1; updatedURL = updateSearchString(" "); refreshGrid();
}
function refreshGrid()
{ $('#SearchResultDataGrid').setGridParam({ url: null }); $('#SearchResultDataGrid').setGridParam({ url: updatedURL }); $('#SearchResultDataGrid').trigger('reloadGrid');
}
I verified JSON requests and they are correct but the problem is I'm not able to append to existing data. I've disabled clearGridData.
Any help would be appreciated.

Related

Cannot read property 'length' of null in script

I'm trying to call a function from code behind in script. That function i just returning list of employee
i'm just trying not to use grid view.
I just copy the code in at the same project and changes the names of function and the name inside the colModel: []
here's my script:
function loadMoretha60grid() {
$('#timesheetgrid').jqGrid("GridUnload");
getmoreThan60(function (data) { loadTimesheetTableMoeretha60(data); });
}
function loadTimesheetTableMoeretha60(timelog) {
var lastsel;
var startpage = 1;
$('#timesheetgrid').jqGrid({
datatype: 'local',
data: timelog,
editurl: 'clientArray',
colNames: ['CompanyID', 'EMPName', 'START_DATE', 'END_DATE',
'TOTALHOURS'],
colModel: [
{ name: 'CompanyID', index: 'CompanyID', editable: 'false', align: 'center', width: '150', sortable: false, },
{ name: 'EMPName', index: 'EMPName', editable: 'false', align: 'center', width: '275', resizable: false },
{ name: 'START_DATE', index: 'START_DATE', editable: 'false', align: 'center', width: '175', resizable: false },
{ name: 'END_DATE', index: 'END_DATE', editable: 'false', align: 'center', width: '175', resizable: false },
{ name: 'TOTALHOURS', index: 'TOTALHOURS', editable: 'false', align: 'center', width: '175', resizable: false },
],
pager: '#timesheetgridpager',
viewrecords: true,
forceFit: false,
shrinkToFit: false,
width: '1000',
emptyrecords: "No Record/s found",
loadtext: "Loading",
rowList: [5, 10, 20, 50],
height: 'auto',
caption: 'Timesheet Listing'
});
$('#timesheetgrid').jqGrid('navGrid', '#timesheetgridpager', {
edit: false,
save: false,
add: false,
cancel: false,
del: false,
search: false,
refresh: false
});
$('#timesheetgrid').jqGrid('inlineNav', '#timesheetgridpager', {
add: false,
edit: false,
save: false,
cancel: false,
restoreAfterSelect: false
});
}
function getmoreThan60(callback) {
var timelog = [],
params = {
name: $('#empnamebox').val(),
dateStart: '2019-09-01',
dateEnd: '2019-09-29'
};
showLoadingGif();
$.ajax({
async: true,
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Timesheet.aspx/getMore60hrs',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
timelog = data.d;
hideLoadingGif();
if (typeof callback != 'undefined')
callback(timelog);
},
error: function (xhr, status, error) {
console.log(xhr, status, error);
hideLoadingGif();
}
});
}
here's my method
[WebMethod]
public static void getMore60hrs(string name,string dateStart,string dateEnd) {
TDKDataAccessLayer dataAcc = new TDKDataAccessLayer();
List<morethan> records = new List<morethan>();
dataAcc.DepartID = Convert.ToInt32(DeptID);
dataAcc.Name = name;
dataAcc.DateStart = dateStart;
dataAcc.DateEnd = dateEnd;
records = dataAcc.MoreThan60hrs();
}
By the way
I don't know what to do about this because i came from windows form c#

jqGrid not filtering

I have implemented the autocomplete filter functionality in my jqGrid.
However this is not working, I believe there are 2 issues.
I have a column which uses a formatter. With this column included, the filtering will not trigger a load at all. Without this column, the filtering will trigger a load, however will not filter the results.
I have read that the index or jsonmap must be the same as the name in the colModel in order for filtering to work. I have ensured that these match, still with no luck.
Code:
loadData: function (someData) {
$(model.table).GridUnload();
$(model.table).jqGrid({
url: $(model.tableURL).val(),
datatype: 'JSON',
mtype: 'POST',
postData: {
someData: someData
},
emptyrecords: 'No Wholesalers',
viewrecords: true,
autowidth: true,
shirnkToFit: false,
rowNum: -1,
loadtext: 'Loading...',
multiselect: false,
width: "100%",
height: "100%",
colModel: [
{ label: 'Wholesaler', name: 'WholesalerName', jsonmap: 'WholesalerName', sortable: false, align: 'center', width: '250' },
{
label: 'Amount Complete', name: 'PercentageComplete', jsonmap:'PercentageComplete', search: false, sortable: false, align: 'center',
formatter: function (cellvalue, options, rowObj) {
return '<div class="progress progress-striped pos-rel" data-percent="' + rowObj.PercentageComplete + '%">' +
'<div class="progress-bar progress-bar-success" style="width:' + rowObj.PercentageComplete + '%;"></div></div>';
}
},
{ label: 'No of Customers', name: 'NoOfCustomers', jsonmap: 'NoOfCustomers', search: false, sortable: false, align: 'center' },
{ label: 'Last Updated', name: 'LastUpdated', jsonmap: 'LastUpdated', search: false, sortable: false, align: 'center' },
{ label: 'Last Update By', name: 'LastUpdateBy', jsonmap: 'LastUpdateBy', search: false, sortable: false, align: 'center' },
],
altrows: true,
loadComplete: function () {
var table = this;
//model.update()
},
loadError: function (xhr, st, err) {
alert(err);
}
}
).jqGrid('filterToolbar', {
stringResult: true, searchOnEnter: false, ignoreCase: true,
})
},
Turns out I didn't have loadonce: true set.
Therefore when filtering on keypress, the grid was being reloaded and re populated with data from the server.

Why my jqgrid is not showing any data?

I want to use a complete jqgrid but it is not working. It is not showing any data but controller action returning the values. Here is my controller action code which is used in my project. My purpose is to use pager in jqgrid. Please help me and i need some solutions & tips for using jqgrid in mvc.
public ActionResult itemList(jqGridViewModel jqGridParameters)
{
var item = from t in db.tbl_Item select t;
var count = item.Count();
int pageIndex = jqGridParameters.page;
int pageSize = jqGridParameters.rows;
int startRow = (pageIndex * pageSize) + 1;
int totalRecords = count;
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var result = new
{
total = totalPages,
page = pageIndex,
records = count,
rows = item.Select(x => new
{
x.id,
x.itemcode,
x.name,
x.qtyLimit,
x.Quantity,
x.sellingPrice,
x.supplier,
x.unitType,
x.vat,
x.batchno,
x.brand,
x.buyingPrice,
x.catg
}
).ToArray()
.ToPagedList(pageIndex, pageSize)
.Select(x => new
{
id = x.id,
cell = new string[] { x.id.ToString(),
x.name,
x.itemcode,
Convert.ToString(x.qtyLimit),
x.Quantity.ToString(),
x.sellingPrice.ToString(),
x.supplier,
x.unitType,
x.vat.ToString(),
x.batchno,
x.brand,
x.buyingPrice.ToString(),
x.catg
}
}
).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
And my view code
jQuery("#list").jqGrid({
cache: false,
async: false,
url: '/Settings/itemList/',
datatype: 'json',
mtype: 'GET',
colNames: ['New Item', 'Batch No', 'Supplier', 'Unit', 'B. Price', 'S. Price','Item Code','Vat','Limit'],
colModel: [
{ name: 'name', index: 'name', width: 110, align: 'center' },
{ name: 'batchno', index: 'batchno', width: 110, align: 'center' },
{ name: 'supplier', index: 'supplier', width: 110, align: 'center' },
{ name: 'unitType', index: 'unitType', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'buyingPrice', index: 'buyingPrice', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'sellingPrice', index: 'sellingPrice', align: 'center' },
{ name: 'itemcode', index: 'itemcode', width: 110, align: 'center'},
{ name: 'vat', index: 'vat', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'qtyLimit', index: 'qtyLimit', align: 'center' }
],
pager: jQuery('#pager'),
rowNum: 15,
rowList: [5, 10, 20, 50],
sortname: 'iid',
sortorder: "desc",
viewrecords: true,
width: 960,
height: 200,
loadOnce: true,
imgpath: '/scripts/themes/coffee/images',
caption: 'Stock Information',
jsonReader: {
root: "Data",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
id: "0"
},
recordtext: "Products {0} - {1} of {2}",
rownumbers: true,
pagerpos: 'center'
});
You define JsonReader like this:
jsonReader: {
root: "Data",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
id: "0"
},
And ther on controller side you passing data to anonimous object that have this properties:
var result = new
{
total = totalPages,
page = pageIndex,
records = count,
...
}
Your property names should be the same as you define in your JsonReader

jqGrid Does Not Show The Returned JSON Data

I use jqGrid in ASP.NET page. In .aspx page, I have -
<div id="divMy" style="width: 100%; overflow: auto;">
<div id="divMyTable" style="width: 97%; display: none;">
<table id="MyTable">
<tr>
<td></td>
</tr>
</table>
<div id="divMyTablePager"></div>
</div>
</div>
In .js file, I have -
var CASortInfo = {
sortname: $('#MyTable').jqGrid('getGridParam', 'sortname'),
sortorder: $('#MyTable').jqGrid('getGridParam', 'sortorder'),
page: $('#MyTable').jqGrid('getGridParam', 'page'),
rows: $('#MyTable').jqGrid('getGridParam', 'rows')
};
$("#MyTable").jqGrid({
url: "../Services/My.asmx/ReadMyTable",
datatype: 'json',
mtype: 'POST',
prmNames: {
search: "isSearch",
nd: null,
rows: "PageSize",
page: "PageNumber",
sort: "sortField",
order: "sortOrder"
},
postData: { ID: $('#hfID').val() },
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
colNames: ["", "My", "Date Created", "Notes", "Action"],
colModel: [
{ name: "MyID", index: "MyID", resizable: false, hidden: true },
{ name: "MyName", index: "MyName", resizable: false, width: 250 },
{ name: "CreatedOn", index: "CreatedOn", resizable: false },
{ name: "Notes", index: "Notes", resizable: false },
{ name: "Buttons", formatter: ActionButtons, width: 70 }
],
sortname: "CreatedOn",
sortorder: "asc",
ignoreCase: true,
autowidth: true,
shrinkToFit: true,
height: "auto",
pager: "#divMyTablePager",
toppager: true,
rowNum: 20,
rowList: [5, 10, 20, 50],
viewrecords: true,
gridview: true,
rownumbers: false,
hoverrows: true,
multiselect: false,
jsonReader: {
root: function (obj) { return obj.d.rows; },
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.records; },
repeatitems: false,
id: "0"
},
beforeRequest: function () {
CASortInfo = {
sortname: $('#MyTable').jqGrid('getGridParam', 'sortname'),
sortorder: $('#MyTable').jqGrid('getGridParam', 'sortorder'),
page: $('#MyTable').jqGrid('getGridParam', 'page'),
rows: $('#MyTable').jqGrid('getGridParam', 'rows')
};
},
gridComplete: function () {
$('#MyTable').jqGrid('setGridParam', {
sortname: CASortInfo.sortname,
sortorder: CASortInfo.sortorder,
page: CASortInfo.page,
rows: CASortInfo.rows
});
$("#divMyTable").show();
$("#MyTable").setGridWidth($("#divMyTable").width());
}
});
I can see the responded JSon data as -
{"d":{"__type":"Core.DTO.JQGridModel","total":"1","page":"1","records":"1","rows":[{"MyID":"627d6ca3-5bbc-4aa8-9e53-76afe4869ae2","MyName":"This\u0027s a test.","CreatedOn":"\/Date(1394135983350)\/","Notes":"Yes","isActive":null}]}}
I can see breakpoint is hit in gridComplete. What needs to be done to show the data grid with data?
Thanks,
Just found out that I messed up the case in divMyTable. After it is corrected, it is working. Thanks

Issues Loading jqGrid with 25,000 Rows

I'm having some difficulty loading my jqGrid with a big amount of rows. Once my document is ready I'm calling a Javascript function that gets a collection of objects from an API and then adds the row data to the grid. Everything has been working fine, but now I have over 20,000 rows, so the grid never loads. Is there something I can do to fix this? Is it possible to only paint the data that the user can see? For example, if the row number on the pager is set to 50, can I simply only load 50 rows and not all 25,000?
Here's my grid:
$(function () {
$("#grid").jqGrid({
datatype: "local",
loadonce: false,
height: "auto",
search: true,
title: false ,
autowidth: true,
shrinkToFit: true,
searchOnEnter: true,
colNames: ['ID', 'BDO Number', 'BDO Date', 'Delivery Date', 'Miles', 'Zip Code', 'Zone', 'Fuel Surcharge', 'Driver', 'Driver Rate', 'Total Driver Pay', 'Order', 'Driver ID',
'Vendor ID', 'Vendor', 'Airport', 'Airline', 'Claim Reference', 'Clear Date', 'Mileage', 'Mileage Cost', 'Special', 'Special Cost', 'Exc Cost', 'Pickup Date', 'Total Delivery Cost',
'Vendor Profit', 'Driver Percent', 'Driver Fuel Surcharge', 'Total Driver Reported', 'Payment', 'User Cleared', 'Excess Costs', 'Additional Fees', 'DriverCostSchemaID'],
colModel: [
{ name: 'ID', index: 'ID', hidden: true },
{ name: 'BDONumber', index: 'BDONumber', align: 'center', classes: 'gridButton' },
{ name: 'BDODate', index: 'BDODate', width: 250, align: 'center', formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'DeliveryDate', index: 'DeliveryDate', width: 250, align: 'center', formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'Miles', index: 'Miles', width: 40, align: 'center' },
{ name: 'ZipCode', index: 'ZipCode', width: 55, align: 'center' },
{ name: 'Zone', index: 'Zone', width: 40, align: 'center' },
{ name: 'FuelFloat', index: 'FuelFloat', width: 50, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'DriverName', index: 'DriverName', width: 125, align: 'center' },
{ name: 'RateFloat', index: 'RateFloat', width: 75, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'PayFloat', index: 'PayFloat', width: 75, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'Order', index: 'Order', hidden: true },
{ name: 'Driver', index: 'Driver', hidden: true },
{ name: 'Vendor', index: 'Vendor', hidden: true },
{ name: 'Airport', index: 'Airport', hidden: true },
{ name: 'Airline', index: 'Airline', hidden: true },
{ name: 'VendorName', index: 'VendorName', hidden: true },
{ name: 'ClaimReference', index: 'ClaimReference', hidden: true },
{ name: 'ClearDate', index: 'ClearDate', hidden: true, formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'Mileage', index: 'Mileage', hidden: true },
{ name: 'MileageCost', index: 'MileageCost', hidden: true, formatter: money },
{ name: 'Special', index: 'Special', hidden: true },
{ name: 'SpecialCost', index: 'SpecialCost', hidden: true, formatter: money },
{ name: 'ExcCost', index: 'ExcCost', hidden: true, formatter: money },
{ name: 'PickupDate', index: 'PickupDate', hidden: true, formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'TotalDeliveryCost', index: 'TotalDeliveryCost', hidden: true, formatter: money },
{ name: 'VendorProfit', index: 'VendorProfit', hidden: true, formatter: money },
{ name: 'DriverPercent', index: 'DriverPercent', hidden: true },
{ name: 'DriverFuelSurcharge', index: 'DriverFuelSurcharge', hidden: true, formatter: money },
{ name: 'TotalDriverReported', index: 'TotalDriverReported', hidden: true, formatter: money },
{ name: 'Payment', index: 'Payment', hidden: true },
{ name: 'UserCleared', index: 'UserCleared', hidden: true },
{ name: 'ExcCost', index: 'ExcCost', hidden: true },
{ name: 'AdditionalFees', index: 'AdditionalFees', hidden: true, formatter: money },
{ name: 'DriverCostSchemaID', index: 'DriverCostSchemaID', hidden: true },
],
rowNum: 100,
rowList: [100, 500, 1000, 100000],
viewrecords: true,
pager: "pager",
sortorder: "desc",
sortname: "DeliveryDate",
ignoreCase: true,
headertitles: true,
emptyrecords: "There are no results.",
})
$("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
GetBDOs();
});
And the GetBDOs function:
function GetBDOs() {
var request = $.ajax({
url: "#Url.Action("GetBDOs", "DPAdmin")",
type: "GET",
cache: false,
async: true,
dataType: "json"
});
request.done(function (results) {
var thegrid = $("#grid");
thegrid.clearGridData();
for (var i = 0; i < 100; i++) {
thegrid.addRowData(i + 1, results[i]);
}
thegrid.trigger("reloadGrid");
});
}
Which calls this:
[Authorize]
public JsonResult GetBDOs()
{
List<BDO> BDOs= new List<BDO>();
// Get all BDOs
BDOs = WebInterface.GetBDOs();
var jsonResult = Json(BDOs.ToArray(), JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
WebInterface.GetBDOs simply hits the database and grabs all the current BDO objects, which is now between 20,000 - 25,000 and freezes the grid. Any help with this?
You really should be paginating that data on the server side before sending it back to the browser. Then all you need to do is fetch the next/prev page and redraw the grid.
The part
var thegrid = $("#grid");
thegrid.clearGridData();
for (var i = 0; i < 100; i++) {
thegrid.addRowData(i + 1, results[i]);
}
thegrid.trigger("reloadGrid");
of GetBDOs function makes performance problems definitively. Instead of calling addRowData in the loop you should set data parameter to results with respect of setGridParam:
var thegrid = $("#grid");
thegrid.clearGridData();
thegrid.jqGrid("setGridParam", {data: results});
thegrid.trigger("reloadGrid");
Additionally it's very important to add gridview: true option to jqGrid.
Even better seems to me to replace use url: "#Url.Action("GetBDOs", "DPAdmin")" as jqGrid parameters together with datatype: "json" and loadonce: true. It will makes the same Ajax call to the server and fill the grid with all 20000 or 25000 rows of data, but placing only 100 first rows in the grid.
One more recommendation will be to use key: true property in ID column. It will inform jqGrid to use the value from ID column as rowid (the value of id attributes of <tr> elements of the grid). You should consider additionally to remove a lot of hidden columns and saves the data only in the internal data option of the grid.

Categories

Resources