Why my jqgrid is not showing any data? - javascript

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

Related

Navgrid not displaying add/delete on JQGrid

Please find my code attached :
Jqgrid creation:
<script type="text/javascript">
$(function () {
$("#datagrid").jqGrid({
url: 'jqgridwithwebmethod.aspx/ConvertDataTabletoString',
datatype: 'json',
mtype: 'POST',
serializeGridData: function (postData) {
// return JSON.stringify(postData);
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
colNames: ['Name', 'Age', 'Mobile', 'City', 'Sex', 'FirstName', 'LatName', 'Address', 'Landline'],
colModel: [
{ name: 'Name', index: 'Name', width: 200, frozen: true, editable: true },
{ name: 'Age', index: 'Age', sorttype: 'int', width: 200, editable: true },
{ name: 'Mobile', index: 'Mobile', sorttype: 'int', width: 200, editable: true },
{ name: 'City', index: 'City', width: 200, editable: true },
{ name: 'Sex', index: 'Sex', width: 200, editable: true },
{ name: 'FirstName', index: 'FirstName', width: 200, editable: true },
{ name: 'LastName', index: 'LastName', width: 200, editable: true },
{ name: 'Address', index: 'Address', width: 200, editable: true },
{ name: 'Landline', index: 'Landline', width: 300, editable: true }
],
pager: '#nav',
rowNum: 10,
sortname: 'Name',
autowidth: true,
sortorder: "desc",
shrinkToFit: false,
//forceFit:false,
loadonce: true,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
jsonReader: {
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
root: function (obj) { return obj.d; },
repeatitems: false
//id: "0"
},
caption: 'My first grid'
});
$("#datagrid").jqGrid('setFrozenColumns');
});
**$('#datagrid').jqGrid('navGrid', '#nav',**
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
});
</script>
The function ConvertDataTabletoString is defined as:
[WebMethod]
public static List<Dictionary<string, object>> ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select * from studen with(nolock)", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
The Jqgrid use data received from SQL server.
The edit/add/delete icons are not dispalying on the Jqgrid..
Kindly help..
You placed call of navGrid method on the wrong place. You have block $(function () {...}); which meany document ready event handler. You placed call of navGrid method out of the block. It's wrong. You should mode it one line above (directly after the call of setFrozenColumns) to fix the problem.

How to display a collection of results to a grid cell using jqGrid

I have a database containing many to many relations, so a Post can have multiple Tags, and a Tag can be assigned to multiple Posts
I am using jqgrid to display all the posts in a grid using the following code:
Javascript:
//grid
jQuery(document).ready(function () {
//post grid
jQuery("#tablePosts").jqGrid({
url: '/Admin/ListPosts/',
datatype: 'json',
mtype: 'GET',
colNames: ['ID', 'Title', 'Short Description', 'Description', 'Category', 'Tags', 'Published', 'Posted Date', 'Modified Date', 'UrlSlug', 'Meta'],
colModel: [
{ name: 'PostID', index: 'PostID', width: 50, stype: 'text' },
{ name: 'Title', index: 'Title', width: 150 },
{ name: 'ShortDescription', index: 'ShortDescription', width: 150, sortable: false },
{ name: 'Description', index: 'Description', width: 200, sortable: false },
{ name: 'Category', index: 'Category', width: 100 },
{ name: 'Tags', index: 'Tags', width: 100, sortable: false},
{ name: 'Published', index: 'Published', width: 80 },
{ name: 'PostedOn', index: 'PostedOn', width: 130 },
{ name: 'Modified', index: 'Modified', width: 130 },
{ name: 'UrlSlug', index: 'UrlSlug', width: 80, sortable: false },
{ name: 'Meta', index: 'Meta', width: 80, sortable: false }
],
rowNum: 10,
rowList: [5, 10, 20, 50],
viewrecords: true,
pager: '#pagerPosts',
height: '100%',
sortname: 'PostedOn',
sortorder: "desc",
//width to null && shrink to false so the width of the grid inherit parent and resizes with the parent
width: null,
shrinkToFit: false
});
});
and this is my controller action:
public ActionResult ListPosts(string sidx, string sord, int page, int rows)
{
int pageNo = page - 1;
int pageSize = rows;
//for paging
int totalRecords = repository.TotalPosts(true) + repository.TotalPosts(false);
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows); //round up to smallest integral number greater than returned valued
//for records
var posts = repository.AllPosts(pageNo, pageSize, sidx, sord == "asc");
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (
from post in posts
select new
{
id = post.PostID,
cell = new string[] {
post.PostID.ToString(),
post.Title,
post.ShortDescription,
post.Description,
post.Category.Name,
post.Tags.ToString(),
post.Published.ToString(),
post.PostedOn.ToString(),
post.Modified.ToString(),
post.UrlSlug,
post.Meta
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
In my rows, I defined post tags as a string just to remove errors and I couldn't figure out how to display Tags as a list, and this is my grid:
as you can see, Tags column is not displaying Tag names, how do you display them correctly?
Insted of post.Tags.ToString() use string.Join(",",post.Tags.Select(t => t.Name))
Or pass array of tags to your view and use custom formatter
Formatter may looks like this:
function tagFormatter(cellvalue, options, rowObject)
{
var text = ""
if (cellvalue.length > 0)
{
for (var i = 0; i < cellvalue.length; i++)
{
text += cellvalue[i].Name;
if (i < cellvalue.length - 1)
{
text += ", ";
}
}
}
return text;
}
It will display comma-separated tags names;
And tag row:
{ name: 'Tags', index: 'Tags', width: 100, sortable: false, formatter: tagFormatter },
Is it helpful?

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.

Append Data to jqGrid

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.

Why doesn't this checkbox column work in this ExtJS grid?

The following ExtJS grid worked until I put the checkbox column in it, now I get this error:
I based the checkbox column code on this code.
What do I need to do to get the checkbox column to work?
var myData = [
[4, 'This is a whole bunch of text that is going to be word-wrapped inside this column.', 0.24, true, '2010-11-17 08:31:12'],
[16, 'Computer2', 0.28, false, '2010-11-14 08:31:12'],
[5, 'Network1', 0.02, false, '2010-11-12 08:31:12'],
[1, 'Network2', 0.01, false, '2010-11-11 08:31:12'],
[12, 'Other', 0.42, false, '2010-11-04 08:31:12']
];
var myReader = new Ext.data.ArrayReader({}, [{
name: 'id',
type: 'int'
}, {
name: 'object',
type: 'object'
}, {
name: 'status',
type: 'float'
}, {
name: 'rank',
type: 'boolean'
}, {
name: 'lastChange',
type: 'date',
dateFormat: 'Y-m-d H:i:s'
}]);
var grid = new Ext.grid.GridPanel({
region: 'center',
style: 'margin: 10px',
store: new Ext.data.Store({
data: myData,
reader: myReader
}),
columns: [{
header: 'ID',
width: 50,
sortable: true,
dataIndex: 'id',
hidden: false
},
{
header: 'Object',
width: 120,
sortable: true,
dataIndex: 'object',
renderer: columnWrap
}, {
header: 'Status',
width: 90,
sortable: true,
dataIndex: 'status'
},
{
xtype: 'checkcolumn',
header: 'Test',
dataIndex: 'rank',
width: 55
},
{
header: 'Last Updated',
width: 120,
sortable: true,
renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s'),
dataIndex: 'lastChange'
}],
viewConfig: {
forceFit: true,
getRowClass: function(record, rowIndex, rp, ds){
if(rowIndex == 2){
return 'red-row';
} else {
return '';
}
}
},
title: 'Computer Information',
width: 500,
autoHeight: true,
frame: true,
listeners: {
'rowdblclick': function(grid, index, rec){
var id = grid.getSelectionModel().getSelected().json[0];
go_to_page('edit_item', 'id=' + id);
}
}
});
You get this error because you have not included the CheckColumn extension. You can get the extension from : http://dev.sencha.com/deploy/dev/examples/ux/CheckColumn.js .. include it and you should be able to remove the error..

Categories

Resources