Display data in jqGrid Footer row in MVC Application - jqgrid

I need help display data in the jqGrid footer row. This is my configuration on the Server. Notice the userdata = (Hours) line.
// Format the data for the jqGrid
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (
from a in activities
select new
{
id = a.ActivityId,
cell = new string[] {
a.ActivityId.ToString(),
DateTime.Parse(a.Date.ToString()).ToShortDateString(),
a.Person.Name.ToString(),
a.ActivityName.ToString(),
a.Hours.ToString()
}
}).ToArray(),
userdata = (Hours)
};
// Return the result in json
return Json(jsonData, JsonRequestBehavior.AllowGet);
The userData amount that I need displayed in the footer is coming through in the JSON. I am using Fiddler to view it. Here is a screenshot of the fiddler view:
alt text http://shirey.technologyblends.com/Content/images/json.jpg
I need to display this value of "12" in the footer. This the HTML I am using to read the JSON:
jQuery("#list").jqGrid({
url: gridDataUrl + '?startDate=' + startDate.toJSONString() + '&endDate=' + endDate.toJSONString(),
datatype: "json",
mtype: 'GET',
colNames: ['Activity ID', 'Date', 'Employee Name', 'Activity', 'Hours'],
colModel: [
{ name: 'ActivityId', index: 'ActivityId', width: 40, align: 'left' },
{ name: 'Date', index: 'Date', width: 50, align: 'left' },
{ name: 'Person.Name', index: 'Person.Name', width: 100, align: 'left', resizable: true },
{ name: 'ActivityName', index: 'ActivityName', width: 100, align: 'left', resizable: true },
{ name: 'Hours', index: 'Hours', width: 40, align: 'left' }
],
loadtext: 'Loading Activities...',
multiselect: true,
rowNum: 20,
rowList: [10, 20, 30],
imgpath: gridimgpath,
height: 'auto',
width: '700',
pager: jQuery('#pager'),
sortname: 'ActivityId',
viewrecords: true,
sortorder: "desc",
caption: "Activities",
footerrow: true, userDataOnFooter: true, altRows: true
}).navGrid('#pager', { search: true, edit: false, add: false, del: false, searchtext: "Search Activities" });

Try to use following
var jsonData = new {
total = totalPages,
page = page,
records = totalRecords,
rows = (
from a in activities
select new {
id = a.ActivityId,
cell = new string[] {
a.ActivityId.ToString(),
DateTime.Parse(a.Date.ToString()).ToShortDateString(),
a.Person.Name.ToString(),
a.ActivityName.ToString(),
a.Hours.ToString()
}
}).ToArray(),
userdata = new {
Hours = 12
}
};
then the userdata part of the JSON data will be
"userdata":{"Hours":12}
which follows to displaying of the bold value 12 in the column Hours of the footer part of the jqGrid table.

Related

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

Date Will Not Filter Correctly After Using Formatter on jqGrid Column

I'm having some issues getting a row of Dates to filter correctly in my jqGrid. Here's a portion of my .cshtml:
<script type="text/javascript">
$(function () {
var width = $(window).width() - 50;
$("#orders_grid").jqGrid({
datatype: "local",
width: width,
height: "auto",
search: true,
autowidth: false,
shrinkToFit: true,
colNames: ['ID', 'Status', 'Category','Sub Category', 'Title', 'Owner', 'Team', 'Priority', 'Release', 'Business Line', 'Created', 'Update'],
colModel: [
{ name: 'ID', width: 12, align: 'center', sorttype: 'int'},
{ name: 'GridStatus', width: 15, align: 'center'},
{ name: 'GridCategory', width: 15, align: 'center'},
{ name: 'GridSubCategory', width: 15, align: 'center'},
{ name: 'Title', width: 60, align: 'left' },
{ name: 'GridOwnerUser', width: 20, align: 'center'},
{ name: 'GridTeam', width: 30, align: 'center'},
{ name: 'GridPriority', width: 12, align: 'center'},
{ name: 'GridRelease', width: 12, align: 'center'},
{ name: 'GridBusinessLine', width: 12, align: 'center'},
{ name: 'CreatedDateTime', width: 14, align: 'center', sortable: true, sorttype: 'd', formatter: dateFix },
{ name: 'LastUpdateDateTime', width: 14, align: 'center', sortable: true, sorttype: 'd', formatter: dateFix }
],
rowNum: 20,
rowList: [20,50,100,1000,100000],
viewrecords: true,
pager: '#gridpager',
sortname: "ID",
sortable: true,
ignoreCase: true,
headertitles: true,
sortorder: "desc",
onSelectRow: function (rowId)
{
var id = $("#orders_grid").getCell(rowId, 'ID');
document.location.href = '/TicketCenter/Display/'+ id;
}
}).navGrid("#orders_grid_pager", { edit: false, add: false, del: false }, {}, {}, {}, { multipleSearch: true, multipleGroup: false, showQuery: false, recreateFilter: true });
$("#orders_grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
setTimeout(function () { searchOrders('#Model.filterFor'); }, 200);
});
function dateFix(LastUpdateDateTime)
{
var x = LastUpdateDateTime.substring(6, LastUpdateDateTime.length - 2);
x = parseInt(x);
x = new Date(x);
x.setMinutes(x.getMinutes() - x.getTimezoneOffset());
x = x.format("mm/dd/yyyy h:MM TT");
return x;
}
function searchOrders(filter)
{
var data = { filter: filter }
var request = $.ajax({
url: "#Url.Action("ListTickets", "TicketCenter")",
type: "GET",
cache: false,
async: true,
data: data,
dataType: "json",
});
request.done(function (orders) {
var thegrid = $("#orders_grid");
thegrid.clearGridData();
setTimeout(function()
{
for (var i = 0; i < orders.length; i++)
{
thegrid.addRowData(i+1, orders[i]);
}
thegrid.trigger("reloadGrid");
}, 500);
});
request.fail(function(orders) {
});
}
</script>
I need to be able to search in the CreatedDateTime and LastUpdateDateTime columns. When I get my data from the database it it initially a datetime. When the grid loads, the date is displayed as "/Date102342523523463246236236", which is obviously in ticks. I formatted this with the dateFix formatter, which returns the date in mm/dd/yyyy h:MM TT format. Now when I try to search by date, I'm getting strange results. I'm thinking that the underlying data is still unformatted and it's searching off of that. Here's an example:
In my database, the CreatedDateTime for one object is 2013-10-11 20:20:10.963.
When the jqGrid loads the data, it shows /Date(1381537210963).
After I add formatter : dateFix to the colModel, it shows 10/11/2013 4:20 PM.
If I type 10 in the search box, it returns that object.
If I type 10/, it doesn't return anything.
If I type 2013, it doesn't return anything.
Is there a way to resolve this issue?
Decided to convert the date to a string in the controller before sending it to the grid. Resolved.

set radiobutton in loadComplete of grid

$("#addressList").jqGrid({
url: '/Storage/Shipping/GetCustomerAddresses?q=2&Customerid=' + $("#saveCustomerID").val(),
datatype: "Json",
jsonReader: {
root: "Data.rows",
page: "Data.page",
total: "Data.total",
records: "Data.records",
repeatitems: true,
userdata: "userdata",
cell: "cell"
},
colNames: ['', 'Line 1', 'Line 2', 'City', 'State'],
colModel: [
{ name: 'myradio', width: 30, fixed: true, align: 'center', resizable: false, sortable: false,
formatter: function (cellValue, option) {
return '<input type="radio" name="radio_' + option.gid + '" />';
}
},
{ name: 'Line1', index: 'Line1', width: 250 },
{ name: 'Line2', index: 'Line2', width: 250 },
{ name: 'City', index: 'City', width: 210 },
{ name: 'State', index: 'State', width: 75 }
],
page: 1,
rowNum: 50,
rowList: [20, 50, 100],
pager: '#pager',
viewrecords: true,
grouping: false,
caption: "Addresses",
mtype: "POST",
width: "100%",
height: "100%",
loadonce: true,
sortable: false,
beforeSelectRow: function (rowid, e) {
var radio = $(e.target).closest('tr').find('input[type="radio"]');
radio.attr('checked', 'checked');
$("#saveCustomerAddressID").val(rowid.toString());
return true; // allow row selection
},
loadComplete: function () {
var grid_ids = $("#addressList").jqGrid('getDataIDs');
for (var i = 0; i < grid_ids.length; i++) {
if ($("#saveCustomerAddressID").val() == grid_ids[i]) {
{
$("#addressList").jqGrid('setSelection', grid_ids[i], true);
}
}
}
}
//, postdata: { CustomerID: $("#saveCustomerID").val() }
});
The above code sets the selection correctly in loadcomplete. The $("#saveCustomerAddressID").val() is the rowid fro the JSON Data.
The radiobutton is set in the beforeSelectRow. I know the row number and grid column of of the radiobutton to be set, but how do you set the radiobutton?
if you have row number and grid column, then it shouldn't be difficult. get the id(css) of that column where you have your radio button(check developer tools for this). now lets say that radio button is in a column name "Demo"
so the id would look like something like this i suppose
var demo= $("'#'+rowid+'Demo'")//check developer tools for confirmation
demo.attr('checked', 'checked');
$("#saveCustomerAddressID").val(rowid.toString());//continue with you loadComplete code
and for set selection use setSelection method of jqgrid after this continue with your code of loadcomplete

Server-side function is called only once in jqGrid

I've put a jqgrid the page. In Jqgrid placed a column that I want when user click on the column, Fill Other Jqgrid.Now when I click on the desired column. Only first-time Fill second JQGrid,But the next time the server side code will not run.
The code is written as follows
var firstButtonColumnIndex = 0;
grid = $('#list'); buttonNames = {};
grid.jqGrid({
url: 'jQGridHandler.ashx?Request=1',
loadonce: true,
direction: "rtl",
pgtext: "صفحه {0} از {1}",
datatype: 'json',
height: 250,
colNames: ['شماره درخواست', 'شماره اموال', 'شرح دستور کار', 'تاریخ دستور کار', 'زمان دستور کار', 'ملاحظات', '', ''],
colModel: [
{ name: 'WorkOrderNo', width: 100, sortable: true },
{ name: 'AssetNo', width: 100, sortable: true },
{ name: 'WorkDescription', width: 400, sortable: true },
{ name: 'WorkOrderDate', width: 80, sortable: true },
{ name: 'WorkOrderTime', width: 80, sortable: true },
{ name: 'Remark', width: 100, sortable: true },
{ name: 'del', width: 20, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-trash'></span>";
}
},
{ name: 'details', width: 20, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-document'></span>";
}
}
],
gridview: true,
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pager',
// sortname: 'WorkOrderNo',
viewrecords: true,
sortorder: 'asc',
caption: 'درخواست ها...........',
rownumbers: true,
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 7) {
//alert("rowid=" + rowid + "\nButton name: " + buttonNames[iCol]);
// $('img').each(function () {
$("#workRequestPopUp").draggable();
// });
} else if (iCol == 8) {
workOrderId = rowid;
$("#tblRequestWorks tr").remove();
$("#tblRequestWorks").jqGrid({
// url: 'jQGridHandler.ashx?RequestWorksFill=1&workOrderId=' + workOrderId,
url: "PublicHandler.ashx?Request=1&workOrderId: rowid",
direction: "rtl",
pgtext: "",
datatype: 'json',
height: 250,
colNames: ['نام کار', 'نام واحد', 'سرپرست واحد', 'تعداد', 'پایان کار', ''],
colModel: [
{ name: 'WorkName', width: 300, sortable: true },
{ name: 'SectionName', width: 100, sortable: true },
{ name: 'SectionSupervisor', width: 100, sortable: true },
{ name: 'RequestCount', width: 80, sortable: true },
{ name: 'FinishWork', width: 100, sortable: true },
{ name: 'details', width: 20, sortable: false, search: false,
formatter: function () {
return "<span class='ui-icon ui-icon-document'></span>";
}
}
],
rowNum: 10,
rowList: [10, 20, 30],
sortorder: 'asc',
caption: 'Test',
rownumbers: true,
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 6) {
alert(rowid);
Fill12(rowid);
} else if (iCol == 8) {
alert(rowid);
Fill12(rowid);
return true;
// return (iCol >= firstButtonColumnIndex) ? false : true;
}
},
dataType: "json"
});
// fillRequestWorkPopup(workOrderId);
popup(e);
}
// prevent row selection if one click on the button
// return (iCol >= firstButtonColumnIndex) ? false : true;
return true;
}
});
It is Delegate Function in tr in JQGrid?
I respected professors can help. thanks All
The URL "PublicHandler.ashx?Request=1&workOrderId: rowid" seems me wrong. Do you mean probably "PublicHandler.ashx?Request=1&workOrderId=" + rowid? The better will be to use url: "PublicHandler.ashx" with postData: {Request: 1, workOrderId: rowid}.
The next problem is the usage of $("#tblRequestWorks tr").remove();. You don't included any HTML code which you use on the page. If you want to destroy the old grid and create a new one on the same place you should use GridUnload instead of $("#tblRequestWorks tr").remove();: $("#tblRequestWorks").jqGrid('GridUnload'); (see here and example).
You can also remove dataType: "json" from the code. jqGrid don't know the option and you already use the correct datatype: "json" option.
I think you can change your code so that the usage of GridUnload will be not needed. Only changing on some parameters of the second grid ($("#tblRequestWorks")) and reloading it with respect of $("#tblRequestWorks").trigger('reloadGrid', [{page: 1}]); seems me enough.
One more remark: you should be very careful in the id values for the second grid. It is not permitted to have id duplicates on the page. If you can't generate unique ids on the server you can consider to use idPrefix option of the grid.

MVC3 Razor Page using jqGrid not rebinding

I have a jqGrid on a view page and it is loaded based on gathering data from a few select lists.
The first time through all is fine. If I change one of the select lists the .change function is triggered but the .jqGrid doesnt fire so the Controller method isnt hit.
My jqGrid code
$("#Builds").change(function () {
var programID = $("#ProgramID").val();
var buildID = $('#Builds').val();
$("#UpdateBuild").show();
// Set up the jquery grid
$("#jqTable").jqGrid({
// Ajax related configurations
url: '#Url.Action("_CustomBinding")',
datatype: "json",
mtype: "POST",
postData: {
programID: programID,
buildID: buildID
},
// Specify the column names
colNames: ["Assembly ID", "Assembly Name", "Cost", "Order", "Budget Report", "Partner Request", "Display"],
// Configure the columns
colModel: [
{ name: "AssemblyID", index: "AssemblyID", width: 40, align: "left", editable: false },
{ name: "AssemblyName", index: "AssemblyName", width: 100, align: "left", editable: false },
{ name: "AssemblyCost", index: "AssemblyCost", width: 40, align: "left", formatter: "currency", editable: true },
{ name: "AssemblyOrder", index: "AssemblyOrder", width: 30, align: "left", editable: true },
{ name: "AddToBudgetReport", index: "AddToBudgetReport", width: 40, align: "left", formatter: "checkbox", editable:true, edittype:'checkbox'},
{ name: "AddToPartnerRequest", index: "AddToPartnerRequest", width: 45, align: "left", formatter: "checkbox", editable:true, edittype:'checkbox'},
{ name: "Show", index: "Show", width: 20, align: "left", formatter: "checkbox", editable:true, edittype:'checkbox'}],
// Grid total width and height and formatting
width: 650,
height: 200,
altrows: true,
// Paging
toppager: true,
pager: $("#jqTablePager"),
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true, // Specify if "total number of records" is displayed
emptyrecords: 'No records to display',
// Default sorting
sortname: "AssemblyID",
sortorder: "asc",
// Grid caption
caption: "Build Template"
}).navGrid("#jqTablePager",
{ refresh: true, add: true, edit: true, del: true },
{}, // settings for edit
{}, // settings for add
{}, // settings for delete
{sopt: ["cn"]} // Search options. Some options can be set on column level
);
});
My controller Code:
[HttpPost]
public JsonResult _CustomBinding(string programID, string buildID, int page, int rows)
{
/* Variable Declarations */
BuildsRepository br = new BuildsRepository();
IEnumerable<ProgramsAssemblyBuilds> pab = br.GetProgramAssembliesBuilds(Convert.ToInt32(programID), Convert.ToInt32(buildID));
// Calculate the total number of pages
var totalRecords = pab.Count();
var totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);
var data = (from s in pab
select new
{
AssemblyID = s.AssemblyID,
cell = new object[] { s.AssemblyID, s.AssemblyName, s.AssemblyCost, s.AssemblyOrder, s.AddToBudgetReport, s.AddToPartnerRequest, s.Show}
}).ToArray();
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = data.Skip((page - 1) * rows).Take(rows)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Anyone have any ideas on this one?
Thanks
You should create the grid only once. So you should place the code
$("#jqTable").jqGrid({ ... });
outside of the change event handler.
To reload the grid you should use
$("#Builds").change(function () {
$("#jqTable").trigger("reloadGrid", [{page: 1}]);
$("#UpdateBuild").show();
});
At the end to have actual values from "#ProgramID" and '#Builds' you should use functions (methods) as the programID and buildID properties of postData:
// Set up the jquery grid
$("#jqTable").jqGrid({
// Ajax related configurations
url: '#Url.Action("_CustomBinding")',
datatype: "json",
mtype: "POST",
postData: {
programID: function() { return $("#ProgramID").val(); },
buildID: function() { return $('#Builds').val(); }
},
...
});
See more information here.

Resources