How To Refresh Google Chart When updating jqGrid - c#

I have a jqGrid in a user control which is placed on an .aspx page. I also have a Google Graph to display the grid data on the same page. Both the grid and chart use Handler1.aspx as the url. Handler1.ashx makes a call to a SQL server and returns JSON.
When initially loading the page, I can see both the graph and the chart go into Handler1.ashx to get the data - so I get a grid and a nice line chart.
The issue is when I update data in the grid, the chart is not updated.
I have tried the SO solution Here without success. I have also tried a button on the page that calls drawChart(). Here is my grid:
$(function () {
$('#dataGrid').jqGrid({
url: 'Handler1.ashx',
datatype: 'json',
mtype: 'POST',
colNames: ["Days", "Origin IB Loads", "Origin OB Loads", "Dest IB Loads", "Dest IB Loads", "ID"],
colModel: [
{ name: 'Days', index: 'Days', width: 100, editable: true, editrules: { required: true }, },
{ name: 'OrigIB', index: 'OrigIB', width: 100, editable: true, editrules: { required: true }, },
{ name: 'OrigOB', index: 'OrigOB', width: 100, editable: true, editrules: { required: true }, },
{ name: 'DestIB', index: 'DestIB', width: 100, editable: true, editrules: { required: true }, },
{ name: 'DestOB', index: 'DestOB', width: 100, editable: true, editrules: { required: true }, },
{ name: 'ID', index: 'ID', width: 80, Key: true, hidden: true }
],
loadonce: false,
pager: '#pagingGrid',
rowNum: 10,
rowList: [10, 20, 30, 'All'],
viewrecords: true,
gridview: true,
autoencode: true,
loadComplete: function (data) {
$(".ui-pg-selbox option[value='All']").val(10000);
},
caption: 'Graph Data',
editurl: 'Handler2.ashx'
});
jQuery("#dataGrid").navGrid("#pagingGrid", {
edit: true,
add: true,
del: true,
search: false,
//searchtext: "Search",
refresh: true
},
{
closeAfterEdit: true,
reloadAfterSubmit: true
},
{
closeAfterAdd: true,
reloadAfterSubmit: true
},
{
reloadAfterSubmit: true
});
})
And here is my Chart - including the grid user control and chart div:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: "handler1.ashx",
dataType: "json",
async: "false",
success: function (jsonData) {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Days');
data.addColumn('number', 'Origin IB Loads');
data.addColumn('number', 'Origin OB Loads');
data.addColumn('number', 'Dest IB Loads');
data.addColumn('number', 'Dest OB Loads');
for (var i = 0; i < jsonData.length; i++) {
data.addRow([jsonData[i].Days, jsonData[i].OrigIB, jsonData[i].OrigOB, jsonData[i].DestIB, jsonData[i].DestOB]);
}
var options = {
title: 'Single Lane Route Quote',
is3D: true,
curveType: 'function',
legend: { position: 'bottom' },
vAxis: { title: "Days" },
hAxis: { title: "Loads" }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
});
}
<My:GridControl ID ="gridControl" runat="server" />
<div id="curve_chart" style="width: 1000px; height: 500px"></div>
How can I get the chart to refresh after making an update in the grid?

what if you tried something like this...
Load Google
Load jqGrid
Load Chart when loadComplete fires on jqGrid
this will allow google to kick things off, then when the grid updates, so will the chart...
google.charts.load('current', {
callback: loadDataGrid,
packages: ['controls', 'table']
});
function loadDataGrid() {
$('#dataGrid').jqGrid({
url: 'Handler1.ashx',
datatype: 'json',
mtype: 'POST',
colNames: ["Days", "Origin IB Loads", "Origin OB Loads", "Dest IB Loads", "Dest IB Loads", "ID"],
colModel: [
{ name: 'Days', index: 'Days', width: 100, editable: true, editrules: { required: true }, },
{ name: 'OrigIB', index: 'OrigIB', width: 100, editable: true, editrules: { required: true }, },
{ name: 'OrigOB', index: 'OrigOB', width: 100, editable: true, editrules: { required: true }, },
{ name: 'DestIB', index: 'DestIB', width: 100, editable: true, editrules: { required: true }, },
{ name: 'DestOB', index: 'DestOB', width: 100, editable: true, editrules: { required: true }, },
{ name: 'ID', index: 'ID', width: 80, Key: true, hidden: true }
],
loadonce: false,
pager: '#pagingGrid',
rowNum: 10,
rowList: [10, 20, 30, 'All'],
viewrecords: true,
gridview: true,
autoencode: true,
loadComplete: function (data) {
$(".ui-pg-selbox option[value='All']").val(10000);
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Days');
chartData.addColumn('number', 'Origin IB Loads');
chartData.addColumn('number', 'Origin OB Loads');
chartData.addColumn('number', 'Dest IB Loads');
chartData.addColumn('number', 'Dest OB Loads');
for (var i = 0; i < data.length; i++) {
chartData.addRow([data[i].Days, data[i].OrigIB, data[i].OrigOB, data[i].DestIB, data[i].DestOB]);
}
var options = {
title: 'Single Lane Route Quote',
is3D: true,
curveType: 'function',
legend: { position: 'bottom' },
vAxis: { title: "Days" },
hAxis: { title: "Loads" }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(chartData, options);
}
},
caption: 'Graph Data',
editurl: 'Handler2.ashx'
});
jQuery("#dataGrid").navGrid("#pagingGrid", {
edit: true,
add: true,
del: true,
search: false,
//searchtext: "Search",
refresh: true
},
{
closeAfterEdit: true,
reloadAfterSubmit: true
},
{
closeAfterAdd: true,
reloadAfterSubmit: true
},
{
reloadAfterSubmit: true
});
}

Related

Paging is not working in jqgrid, loadonce : false

I want to display json data in jqgrid. I have given loadonce as false, the total records is showing properly in grid pager but the page index is always 1 of 1. any help is appreciated.
Code:
var LoadCDHDetailsGrid = function (backstageViewByVal, bossStoreDate, filterflag, getBackStageDataFromCache, inboundViewType, carrierViewBy, featured) {
BackstageInboundbuildSearchFilters();
var mygridwidth = $('.tablegriddiv').width();
var defaultSort = "expectedDeliveryDate";
var url = featured ? '/Inbound/RetrieveFeaturedInboundData/' : '/Inbound/RetrieveCDHInboundDetailsData/';
jQuery("#BackStageGrid").jqGrid({
url: url,
postData: { searchfilters: JSON.stringify(BackstageAdvfilters), advf: advf, customsortname: customsortname, customsortorder: customsortorder, filterflag: filterflag, storeDt: bossStoreDate, GetFromCache: getBackStageDataFromCache, packageType: inboundViewType, selectedviewTransfers: backstageViewByVal, carrierView: carrierViewBy },
datatype: 'json',
mtype: 'POST',
colNames: ['Tracking #', 'Carton #', 'Delivery Date', 'Status', 'Status Date', 'Status Time'],
colModel: [
{ name: 'bakTrackingNbr', jsonmap: 'trackingLabelNbr', index: 'trackingLabelNbr', width: 170, formatter: commonWorkloadFunctions.trackingHyperlinkFormatter, unformat: commonWorkloadFunctions.trackingnHyperlinkUnFormatter, align: 'center', search: true, classes: "underlineres" },
{ name: 'bakCarton', jsonmap: 'cartonNumber', index: 'cartonNumber', width: 145, align: 'center', search: true, formatter: commonWorkloadFunctions.cdhCartonHyperlinkFormatter, unformat: commonWorkloadFunctions.cartonHyperlinkUnFormatter, classes: "underlineres" },
//Added for SSW2- 292
{ name: 'bakExpectedDelDate', jsonmap: 'expectedDeliveryDateTime', index: 'expectedDeliveryDate', width: 125, align: 'center', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y" }, search: true },
{
name: 'bakStatus', jsonmap: 'status', index: 'Status', width: 150, align: 'center', formatter: 'select',
edittype: 'select', editoptions: {
value: workloadGridDropdownColumnsList.statusListBackstage(),
defaultValue: 'ALL',
multiple: true,
width: '200'
},
stype: 'select', searchoptions: {
sopt: ['eq', 'ne'],
value: workloadGridDropdownColumnsList.statusListInBoundBackstage(),
attr: { multiple: 'multiple', size: 5 },
dataInit: dataInitMultiselect
}
},
{ name: 'bakStatusDate', jsonmap: 'statusDate', index: 'StatusDate', width: 100, align: 'center', search: true },
{ name: 'bakStatusTime', jsonmap: 'statusTime', index: 'StatusTime', width: 80, align: 'center', search: false },
],
pager: '#BackStageGridPager',
rowNum: 30,
width: mygridwidth,
gridview: true,
ignoreCase: true,
cmTemplate: { resizable: false },
sortname: 'trackingLabelNbr',
sortname: defaultSort,
viewrecords: true,
sortorder: 'asc',
sortable: false,
scrollable: true,
loadonce: false,
shrinkToFit: true,
onSelectRow: function (rowid, status, e) {
backstageGridBuiltinFunctions.backstageGridOnSelectRow(rowid, status, e);
},
beforeRequest: function () {
if (toolbarBackStatusSel.length == 0) {
$("input:checkbox[name=multiselect_gs_bakStatus]:checked").each(function () {
toolbarBackStatusSel.push($(this).attr('value'));
bakstatusValue += $(this).attr('value') + ",";
});
if (bakstatusValue.length >= 1 && advfilters !== '') {
for (var i = 0; i < advfilters.length; i++) {
if (advfilters[i].SearchingName == 'Status')
advfilters.splice(i, 1);
}
advfilters.push({ SearchingName: "Status", SearchingValue: (bakstatusValue.replace(/,\s*$/, '')) });
}
}
jQuery("#BackStageGrid").jqGrid('setGridParam', { postData: { searchfilters: JSON.stringify(advfilters), advf: advf, customsortname: customsortname, customsortorder: customsortorder, filterflag: filterflag, storeDt: bossStoreDate, GetFromCache: getBackStageDataFromCache, packageType: inboundViewType, selectedviewTransfers: backstageViewByVal, carrierView: carrierViewBy } });
if (typeof $("#gs_bakTrackingNbr").val() !== 'undefined') {
baktrackingNoValue = $("#gs_bakTrackingNbr").val();
}
if (typeof $("#gs_bakCarton").val() !== 'undefined') {
bakcartonNoValue = $("#gs_bakCarton").val();
}
if (typeof $("#gs_bakExpectedDelDate").val() !== 'undefined') {
bakexpectedDelDateValue = $("#gs_bakExpectedDelDate").val();
}
if (typeof $("#gs_bakPackageType").val() !== 'undefined') {
bakpackageTypeValue = $("#gs_bakPackageType").val();
}
if (typeof $("#gs_bakStatusDate").val() !== 'undefined') {
bakstatusDateValue = $("#gs_bakStatusDate").val();
}
if (typeof $("#gs_bakStatusTime").val() !== 'undefined') {
bakstatusTimeValue = $("#gs_bakStatusTime").val();
}
},
onPaging: function () {
filterflag = false;
getBackStageDataFromCache = true;
},
loadComplete: function (data) {
backstageGridBuiltinFunctions.backstageGridViewLoadComplete(data);
},
loadError: function (xhr, status, error) {
filterflag = true;
getBackStageDataFromCache = false;
commonFunctions.spmDialogueAlert("Data service connectivity error.");
commonWorkloadFunctions.hideLoadingMessage();
},
height: "400",
timeout: 600000
}).trigger("reloadGrid");
var theGrid = jQuery("#BackStageGrid");
theGrid.jqGrid('navGrid', '#BackStageGridPager', { refreshstate: 'current', edit: false, refresh: false, search: false, del: false, add: false });
theGrid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: myDefaultSearch, beforeSearch: BackStageInboundBeforeSearchHandler });
};
I have tried using loadonce as true. then the pagination is working, but when searching a value the grid is blank. no records is returning. my data is returning from a web service. the is no issue with the data.
I was able to resolve the issue by sending record count, page index along with data. which I was not sending previously.

jqxGrid: conditionally add edit button per row

i have jqxGrid and display data fine using ajax request and everything is workig fine .
My problem : in grid coulmns i added edit button but i want to add this button conditionally depended on values of another field
My Code :
$(document).ready(function () {
$("#btnsearchHistory").click(function () {
var txtfrom = $('#txtfrom').val();
var txtto = $('#txtto').val();
var terminalId = $('#txtMerchantAccounthistory').val();
var SOFAccount = $('#txtsalesNumber').val();
var statMsg = $('#drpStatMsg').val();
var formatedData = '';
var totalrecords = 0;
if (txtfrom == "") {
alert("Select Valid From Date");
event.returnValue = false;
return false;
}
if (txtto == "") {
alert("Select Valid To Date");
event.returnValue = false;
return false;
}
var source = {
datatype: "json",
datafields: [
{ name: 'Id' },
{ name: 'TerminalId' },
{ name: 'UserName' },
{ name: 'Error' },
{ name: 'Date' },
{ name: 'SalesAccount' },
{ name: 'BillTypeCode' },
{ name: 'Amount' },
{ name: 'BillerCode' },
{ name: 'BankID' },
{ name: 'ReqId' }
],
sort: function () {
$("#grid").jqxGrid('updatebounddata', 'sort');
},
filter: function () {
$("#grid").jqxGrid('updatebounddata', 'filter');
},
beforeprocessing: function (data) {
var returnData = {};
data = data.d;
totalrecords = data.count;
returnData.totalrecords = data.count;
returnData.records = data.data;
if (data.data != null) {
return returnData;
}
return data;
},
type: 'Get',
sortcolumn: 'Id',
sortdirection: 'desc',
formatdata: function (data) {
data.pagenum = data.pagenum || 0;
data.pagesize = data.pagesize || 10;
data.sortdatafield = data.sortdatafield;
data.sortorder = data.sortorder || 'asc';
data.filterscount = data.filterscount || 0;
formatedData = buildQueryString(data);
return formatedData;
},
url: '/WS/WS.asmx/SearchTransferLog',
data: { fromDate: JSON.stringify(txtfrom), toDate: JSON.stringify(txtto), terminalId: JSON.stringify(terminalId), SOFAccount: JSON.stringify(SOFAccount), statMsg: JSON.stringify(statMsg) },
};
var dataAdapter = new $.jqx.dataAdapter(source, {
contentType: 'application/json; charset=utf-8',
loadError: function (xhr, status, error) {
alert(error);
}
});
var cols = [
{ text: 'Id', dataField: 'Id', hidden: true },
{ text: 'رقم حساب التاجر', dataField: 'TerminalId', width: '28%', align: "right", cellsalign: "right", hidden: true },
{ text: '', dataField: 'UserName', width: '28%', align: "right", cellsalign: "right", hidden: true },
{ text: 'الحالة', dataField: 'Error', width: '28%', align: "right", cellsalign: "right" },
{ text: 'تاريخ الدفع', dataField: 'Date', width: '18%', align: "right", cellsalign: "right" },
{ text: 'حساب الدفع', dataField: 'SalesAccount', width: '15%', align: "right", cellsalign: "right" },
{ text: 'توقعات الاغلاق على', dataField: 'BillTypeCode', width: '15%', align: "right", cellsalign: "right", hidden: true },
{ text: 'القيمة المحولة', dataField: 'Amount', width: '15%', align: "right", cellsalign: "right" },
{ text: 'توقعات الاغلاق على', dataField: 'BillerCode', width: '15%', align: "right", cellsalign: "right", hidden: true },
{ text: 'توقعات الاغلاق على', dataField: 'BankID', width: '15%', align: "right", cellsalign: "right", hidden: true },
{ text: 'توقعات الاغلاق على', dataField: 'ReqId', width: '15%', align: "right", cellsalign: "right", hidden: true },
{
text: '', datafield: 'Edit', columntype: 'button', width: '100px', cellsrenderer: function () {
return "استعلام عن الحالة";
}, buttonclick: function (row) {
var id = $("#detail_grid").jqxGrid('getcellvalue', row, "Id");
alert(id);
//RefreshTransferStatus();
}
}
];
$("#detail_grid").jqxGrid({
source: dataAdapter,
pageable: true,
autoheight: true,
virtualmode: true,
sorttogglestates: 1,
filterable: true,
sortable: true,
rtl: true,
altrows: true,
width: '100%',
rendergridrows: function (args) {
return args.data;
},
columns: cols
});
});
});

Index was out of range while accessing list count

I am facing very strange scenario. i have a list of customer and on the basis of some condition i am filtering that list. for example if user search for email i filter it out to get records matches which particular email. Also i am calculating paging as well which works well in case of first page 1. but when i try to give it 2 page it gives me strange behavior. first look into the code below .
For page 1 this line of code works well
int total = _customerlist.Count();
but when i have second page in parameter it gives me "Index was out of range. Must be non-negative and less than the size of the collection." error. however i still have records in both cases 10 records in page 1 and 5 records in page 2. so when i get this error i have 5 records in "_customerlist"
why i am not getting this error when i have page 1?
Controller
public ActionResult CustomerList(int page, int rp, string sortname, string sortorder, string qtype, string query)
{
var _customerlist = _customerRepository.Table;
if (!string.IsNullOrEmpty(qtype) && !string.IsNullOrEmpty(query))
{
if (qtype == "Email")
{
_customerlist = _customerlist.Where(p => p.Email.Contains(query));
}
else if (qtype == "LastName")
{
_customerlist = _customerlist.Where(p => p.LastName.Contains(query));
}
else if (qtype == "FirstName")
{
_customerlist = _customerlist.Where(p => p.FirstName.Contains(query));
}
else if (qtype == "Age")
{
_customerlist = _customerlist.Where(p => p.Age.ToString().Contains(query));
}
else if (qtype == "Sex")
{
_customerlist = _customerlist.Where(p => p.Sex.ToString().Contains(query));
}
else if (qtype == "Email")
{
_customerlist = _customerlist.Where(p => p.Email.ToString().Contains(query));
}
else if (qtype == "MembershipType")
{
_customerlist = _customerlist.Where(p => p.MembershipType.ToString().Contains(query));
}
}
_customerlist = _customerlist.Skip((page - 1) * rp).Take(rp);
int total = _customerlist.Count();
return CreateFlexiJson(_customerlist, page, total);
}
private JsonResult CreateFlexiJson(IEnumerable<CustomerPartRecord> items, int page, int total)
{
List<Object> rows = new List<Object>();
foreach (var item in items)
{
var familystring = string.Empty;
if (item.MembershipType == "Family")
{
var familymembers = from p in _familyRepository.Table.Where(p => p.UserId == item.Email) select p;
int i = 1;
foreach (var familyitem in familymembers)
{
if (i == 1)
{
familystring = familystring + "<label style=\"" + "color:#2B3856;font-weight: bold;" + "\">" + item.FirstName + " " + item.LastName + " (Head)</label>";
familystring = familystring + "<hr>" + "</hr>";
familystring = familystring + "<label style=\"" + "color:#2B3856;" + "\">" + familyitem.FirstName + " " + familyitem.LastName + "</label>";
}
else
{
familystring = familystring + "<label style=\"" + "color:#2B3856;" + "\">" + familyitem.FirstName + " " + familyitem.LastName + "</label>";
}
i++;
}
}
else
{
familystring = "N/A";
}
rows.Add(new
{
id = item.Id,
cell = new string[] {
item.Id.ToString(),
item.FirstName,
item.LastName,
item.Email,
item.HouseNameOrNumber,
item.Street,
item.County,
item.Town,
item.Age.ToString(),
item.Sex,
item.BCUMembershipNumber,
item.MembershipType,
item.PostCode,
item.HomePhone,
item.MobilePhone,
item.DOB,
item.EmergencyContactName,
item.EmergencyContactAddress,
item.EmergencyContactPhone,
item.EmergencyContactMobile,
item.EmergencyContactEmail,
item.CreatedUtc.ToShortDateString(),
String.Format(familystring),
String.Format("View") ,
}
});
}
var result = new { page = page, total = total, rows = rows };
return Json(result);
}
cshtml
$('#CustomerList').flexigrid({
url: '#Url.Action("CustomerList", "Customer")',
dataType: 'json',
colModel: [
{
display: 'Id',
name: 'Id',
width: 150,
sortable: true,
align: 'left',
hide: true
},
{
display: 'First Name',
name: 'FirstName',
width: 80,
sortable: true,
align: 'left'
},
{
display: 'Last Name',
name: 'LastName',
width: 80,
sortable: true,
align: 'left'
},
{
display: 'Email',
name: 'Email',
width: 140,
sortable: true,
align: 'left'
},
{
display: 'HouseNameOrNumber',
name: 'HouseNameOrNumber',
width: 200,
sortable: true,
align: 'left',
hide: true
},
{
display: 'Street',
name: 'Street',
width: 200,
sortable: true,
align: 'left',
hide: true
},
{
display: 'County',
name: 'County',
width: 200,
sortable: true,
align: 'left',
hide: true
},
{
display: 'Town',
name: 'Town',
width: 200,
sortable: true,
hide: true,
align: 'left'
},
{
display: 'Age',
name: 'Age',
width: 30,
sortable: true,
align: 'left'
},
{
display: 'Sex',
name: 'Sex',
width: 30,
sortable: true,
align: 'left'
},
{
display: 'B.C.U',
name: 'BCUMembershipNumber',
width: 60,
sortable: true,
align: 'left'
},
{
display: 'Membership Type',
name: 'MembershipType',
width: 100,
sortable: true,
align: 'left'
},
{
display: 'Post Code',
name: 'PostCode',
width: 100,
sortable: true,
align: 'left',
hide: true,
},
{
display: 'Home Phone',
name: 'HomePhone',
width: 100,
sortable: true,
align: 'left',
hide: true,
},
{
display: 'Mobile Phone',
name: 'MobilePhone',
width: 100,
sortable: true,
align: 'left',
hide: true,
},
{
display: 'DOB',
name: 'DOB',
width: 100,
sortable: true,
align: 'left',
hide:true
},
{
display: 'EmergencyContactName',
name: 'EmergencyContactName',
width: 100,
sortable: true,
align: 'left',
hide:true
},
{
display: 'EmergencyContactAddress',
name: 'EmergencyContactAddress',
width: 100,
sortable: true,
align: 'left',
hide:true
},
{
display: 'EmergencyContactPhone',
name: 'EmergencyContactPhone',
width: 100,
sortable: true,
align: 'left',
hide:true
},
{
display: 'EmergencyContactMobile',
name: 'EmergencyContactMobile',
width: 100,
sortable: true,
align: 'left',
hide:true
},
{
display: 'EmergencyContactEmail',
name: 'EmergencyContactEmail',
width: 100,
sortable: true,
align: 'left',
hide:true
},
{
display: 'Member Since',
name: 'CreatedUtc',
width: 70,
sortable: true,
align: 'left',
},
{
display: 'Family',
name: '',
width: 150,
sortable: true,
align: 'left'
},
{
display: 'Other Info.',
name: '',
width: 50,
sortable: true,
align: 'left'
}
],
buttons: [
{
name: 'Edit',
bclass: 'edit',
onpress: test
}, {
name: 'Delete',
bclass: 'delete',
onpress: test
}, {
separator: true
}],
searchitems: [
{
display: 'First Name',
name: 'FirstName'
},
{
display: 'Last Name',
name: 'LastName'
},
{
display: 'Email',
name: 'Email'
},
{
display: 'Age',
name: 'Age'
},
{
display: 'Sex',
name: 'Sex'
},
{
display: 'Membership Type',
name: 'MembershipType'
}
],
sortname: "LastName",
sortorder: "asc",
usepager: true,
title: 'Customer',
useRp: true,
rp: 10,
showTableToggleBtn: true,
width: 920,
height: 500,
singleSelect: true
});
Try to use Dynamic Linq
Dynamic WHERE clause in LINQ
https://msdn.microsoft.com/ru-ru/vstudio/bb894665.aspx

Jqgrid not displaying after hosting in iss

i have created a report form using jqgrid 4.7 in asp.net web form
in asp.net 4.0.
it works fine in local visual studio but not working after hoisting In IIS
page displaying Empty.
i have posted my script below,
please suggest me some solutions.
-------here my code---- do needfull, thanx in advance.
jQuery(document).ready(function () {
jQuery.extend(jQuery.jgrid.edit, {
closeAfterEdit: true,
closeAfterAdd: true,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata);;
}
});
jQuery.extend(jQuery.jgrid.del, {
ajaxDelOptions: { contentType: "application/json" },
onclickSubmit: function (eparams) {
var retarr = {};
var sr = jQuery("#datagrid").getGridParam('selrow');
rowdata = jQuery("#datagrid").getRowData(sr);
retarr = { PID: rowdata.PID };
return retarr;
},
serializeDelData: function (data) {
var postData = { 'data': data };
return JSON.stringify(postData);
}
});
filters = {
"groupOp": "AND", "rules": [{ "field": "id", "op": "gt", "data": "1" },
{ "field": "name", "op": "bw", "data": "Client" }]
}
$("#datagrid").jqGrid({
url: 'MIS.aspx/GetMIS',
datatype: 'json',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: { root: "d.rows", page: "d.page", total: "d.total", records: "d.records", cell: "cell", id: "0", /* index of the column with the PK in it userdata: "userdata",*/ repeatitems: false },
colNames:['Customer Name', 'Handling Branch', 'Handler Name', 'Transaction Origin', 'Last Action', 'Last Action Date', 'Reason', 'EnquiryNo', 'QuoteRefNo',
'SaleorderNo', 'Enquiry Created By', 'Enquiry Created Date', 'Assigned Date', 'Enquiry Mode', 'Enquiry Reference', 'Quote Submitted For Approval',
'Manager', 'Quote Approved Date', 'Quote Sent Date', 'Quote Value', 'PurchaseOrder Value ', 'PurchaseOrder No', 'PurchaseOrder Date', 'Reference', 'PO Type', 'SalesOpportunity',
],
colModel: [
{
name: 'CustomerName', index: 'CustomerName',
searchoptions: {sopt: ['eq', 'cn']}, searchrules: { "required": true }, width: 150, sortable: true, sorttype: 'text'
},
{ name: 'HandlerBranch', index: 'HandlerBranch', searchoptions: { sopt: ['eq', 'cn'] }, width: 100, searchrules: { "required": true }, sorttype: 'text' },
{ name: 'HandlerName', index: 'HandlerName', searchoptions: { sopt: ['eq', 'cn'] }, width: 100, searchrules: { "required": true }, sorttype: 'text' },
{ name: 'TransactionOrigin', index: 'TransactionOrigin', searchoptions: { sopt: ['eq', 'cn'] }, width: 100, searchrules: { "required": true }, sorttype: 'text' },
{ name: 'LastAction', index: 'LastAction',width: 150, stype: "select",
searchoptions: {
value: getStatus(), sopt: ['cn']
}, sorttype: 'text'
},
{ name: 'LastActionDate', index: 'LastActionDate', width: 100,sorttype:'date',
searchoptions: {
sopt: ['eq','ge', 'le'],
dataInit: function (element) {
$(element).datepicker({
id: 'ActionDate_datePicker',
dateFormat: 'dd-mm-yy',
showOn: 'focus'
});
}
},
sortable: true, width: 100, searchrules: { "required": true }
},
{ name: 'Reason', index: 'Reason', searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true }, width: 100, sorttype: 'text' },
{ name: 'EnquiryNo', index: 'EnquiryNo', width: 100, searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true }, sorttype: 'text' },
{ name: 'QuoteRefNo', index: 'QuoteRefNo', width: 100, searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true }, sorttype: 'text' },
{ name: 'SaleOrderNo', index: 'SaleOrderNo', width: 100, searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true }, sorttype: 'text' },
{ name: 'EnquiryCreatedBy', index: 'EnquiryCreatedBy', width: 100, searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true }, sorttype : 'text' },
{ name: 'EnquiryCreatedDate', width: 100, index: 'EnquiryCreatedDate',
searchoptions: {
sopt: ['eq','ge', 'le'],sorttype: 'date',
dataInit: function (element) {
$(element).datepicker({
id: 'ActionDate_datePicker',
dateFormat: 'dd-mm-yy',
//minDate: new Date(2010, 0, 1),
// maxDate: new Date(2020, 0, 1),
showOn: 'focus'
});
}
}, searchrules: { "required": true }
},
{ name: 'AssignedDate', index: 'AssignedDate', width: 100,
searchoptions: {
sopt: ['eq', 'ge', 'le'], sorttype: 'date',
dataInit: function (element) {
$(element).datepicker({
id: 'AssignedDate_datePicker',
dateFormat: 'dd-mm-yy',
//minDate: new Date(2010, 0, 1),
//maxDate: new Date(2020, 0, 1),
showOn: 'focus'
});
}
}, width: 100, searchrules: { "required": true }
},
{ name: 'EnquiryMode', index: 'EnquiryMode', width: 100, sorttype: 'text', searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true } },
{ name: 'EnquiryReference', index: 'EnquiryReference', sorttype: 'text', width: 100, searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required" : true } },
{ name: 'QuotesubmitedForApproval', index: 'QuotesubmitedForApproval', width: 200, sorttype: 'date',
searchoptions: {
sopt: ['ge', 'le'],
dataInit: function (element) {
$(element).datepicker({
id: 'yetoappDate_datePicker',
dateFormat: 'dd-mm-yy',
showOn: 'focus'
});
}
}, searchrules: { "required": true }
},
{ name: 'Manager', index: 'Manager', width: 100, sorttype: 'text', searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true } },
{ name: 'QuoteApprovedDate', index: 'QuoteApprovedDate', width: 100, sorttype: 'date',
searchoptions: {
sopt: ['ge', 'le'],
dataInit: function (element) {
$(element).datepicker({
id: 'ApprovedDate_datePicker',
dateFormat: 'dd-mm-yy',
showOn: 'focus'
});
}
}, searchrules: { "required": true }
},
{ name: 'QuoteSentDate', index: 'QuoteSentDate', width: 100, sorttype: 'date',
searchoptions: { sopt: ['eq','ge', 'le'] ,
dataInit: function (element) {
$(element).datepicker({
id: 'QuotesentDate_datePicker',
dateFormat: 'dd-mm-yy',
//minDate: new Date(2010, 0, 1),
// maxDate: new Date(2020, 0, 1),
showOn: 'focus'
});
}
}, searchrules: { "required": true }
},
{ name: 'QuoteValue', index: 'QuoteValue', sorttype: 'date', width: 100, searchoptions: { sopt: ['eq', 'ge', 'le'] }, searchrules: {
"required": true,
"number": true
}
, sorttype: 'number'
},
{ name: 'PurchaseOrderValue', index: 'PurchaseOrderValue', searchoptions: { sopt: ['eq', 'ge', 'le'] }, width: 100,
searchrules: {
"required": true,
"number": true
}, sorttype: 'number'
},
{ name: 'PurchaseOrderNo', index: 'PurchaseOrderNo', sorttype: 'date', searchoptions: { sopt: ['eq', 'cn'] }, width: 100, searchrules: { "required": true } },
{ name: 'PurchaseOrderDate', index: 'PurchaseOrderDate', sorttype: 'date', width: 100,
searchoptions: {
sopt: ['eq', 'ge', 'le'],
dataInit: function (element) {
$(element).datepicker({
id: 'PODate_datePicker',
dateFormat: 'dd-mm-yy',
//minDate: new Date(2010, 0, 1),
//maxDate: new Date(2020, 0, 1),
showOn: 'focus'
});
}
}
,searchrules: { "required": true }
},
{ name: 'Reference', index: 'Reference', width: 100, sorttype: 'text', searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true } },
{ name: 'PuchaseOrdertype', index: 'PuchaseOrdertype', sorttype: 'text', searchoptions: { sopt: ['eq', 'cn'] }, searchrules: { "required": true }
},
{ name: 'SalesOpportunity', index: 'SalesOpportunity', sorttype: 'text', stype: "select", width: 150,
searchoptions: {
clearSearch: false,
value: "open:Open;Closed:Closed;Drop:Drop;Lost:Lost", sopt: ['eq'],
//buildSelect: createSelectList,
//attr: { multiple: 'multiple', size: 2 },
//dataInit: dataInitMultiselect,
//buildSelect: createSelectList
},
searchrules: { "required": true }
},
],
//footerrow: true,
//userDataOnFooter: true,
rowNum: 50,
rowList: [10, 20, 50, 100],
shrinkToFit: false,
//sortable: false,
autoencode: true,
sortname: 'LastActionDate',
sortorder: "Asc",
multiselect: false,
frozenColumns: false,
ReorderCoulmns : true,
ignoreCase: true,
pager: "#navGrid",
viewrecords: true,
gridview: false,
width: 1200,
height: 500,
//rownumbers: true, // show row numbers
rownumWidth: 25, // the width of the row numbers columns
//loadComplete: loadCompleteHandler1,
ondblClickRow: function (rowid) {
jQuery(this).jqGrid('viewGridRow', rowid);
},
//beforeRequest: function () //loads the jqgrids state from before save
//{
// modifySearchingFilter.call(this, ',');
//},
sortable: {
update: function (perm) {
if (perm) {
$("#datagrid").jqGrid("remapColumns", perm, true);
var colModels = $("#navGrid").getGridParam("colModel");
}
}
},
caption: 'MIS Report',
loadError: function (xhr, textStatus, errorThrown) {
var errorMsg = xhr.responseText;
var msg = "Some errors occurred during processing:";
msg += '\n\n' + textStatus + '\n\n' + errorMsg;
//g.trackError(msg, document.URL, 0);
}
});
$('#datagrid').navGrid("#navGrid", {
search: true, // show search button on the toolbar
add: false,
edit: false,
del: false,
refresh: true,
position: "left", cloneToTop: true
},
{}, // edit options
{}, // add options
{}, // delete options
{
closeOnEscape: true, multipleSearch: true, overlay: false,
closeAfterSearch: true
} // search options - define multiple search
);
$.extend(true, $.ui.multiselect, {
locale: {
addAll: 'Make all visible',
removeAll: 'Hidde All',
itemsCount: 'Avlialble Columns'
}
});
$('#datagrid').jqGrid('navButtonAdd', '#navGrid', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
onClickButton: function () {
debugger
$("#datagrid").jqGrid('columnChooser',
{
width: 550, msel_opts: { dividerLocation: 0.5 }, modal: true,
done: function (perm) {
debugger
if (perm) {
// "OK" button are clicked
$("#datagrid").jqGrid("remapColumns", perm, true);
// the grid width is probably changed co we can get new width
// and adjust the width of other elements on the page
// var gwdth = $("#datagrid").jqGrid("getGridParam", "width");
// $("#datagrid").jqGrid("setGridWidth", 1200);
//} else {
// // we can do some action in case of "Cancel" button clicked
}
}
});
}
});
$('#datagrid').navButtonAdd('#navGrid', {
caption: "Export",
buttonicon: "ui-icon-disk",
onClickButton:
function () {
debugger
var d = new Date();
var filename = "MISExport_" + d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear().toString() + ".xlsx";
//jQuery("#datagrid").jqGrid('jqGridExport', options);
ExportJQGridDataToExcel("#datagrid", filename);
},
position: "last"
});
$("#datagrid").jqGrid("setFrozenColumns");
});

Setting default Value Inline Add Jqgrid

Currently I have a requirement in a system where I need to repeat much of the data from the last row entered.
Actualy this is my Grid:
$('#list').jqGrid({
colNames: ['VendedorId', 'Vendedor', 'Especie', 'Cabezas', 'Kilos', 'Precio', 'Guías Venta', 'Vencimiento'],
colModel: [
{ hidden: true, name: 'VendedorId' },
{ editable: true, width: 160, edittype: 'select', editoptions: { dataUrl: '/Clientes/CmbClientes' }, editrules: { required: true }, name: 'Vendedor' },
{ editable: true, width: 70, edittype: 'select', editoptions: { dataUrl: '/Especies/CmbEspecie' }, editrules: { required: true }, name: 'Especie' },
{ align: 'right', width: 50, editable: true, editoptions: { size: 3, maxlength: 3 }, editrules: { number: true }, formatter: 'number', formatoptions: { decimalPlaces: 0 }, name: 'Cabezas' },
{ align: 'right', width: 50, editable: true, editrules: { number: true }, formatter: 'number', formatoptions: { decimalPlaces: 0 }, name: 'Kilos' },
{ align: 'right', width: 50, editable: true, editrules: { number: true, required: true }, formatter: 'currency', formatoptions: { prefix: '$',decimalPlaces: 2 }, name: 'Precio' },
{ editable: true, width: 50, editoptions: { maxlength: 20 }, name: 'GuiasVenta' },
{ align: 'right', width: 70, editable: true, editoptions: { size: 3, maxlength: 3 }, editrules: { number: true, required: true }, formatter: 'number', formatoptions: { decimalPlaces: 0 }, name: 'Vencimiento' }
],
url: '#Url.Action("ListVendedores")',
datatype: 'json',
editurl: '#Url.Action("SaveVendedor")',
mtype: 'POST',
pager: '#vendedoresPager',
prmNames: { id: 'RemateId' },
rowList: [5, 10, 15, 20],
sortname: 'FeriaId',
viewrecords: true,
width: 850
}).jqGrid('navGrid', '#vendedoresPager', { add: false, edit: false, del:true ), search: false },{},{},{ url: '/Remates/BorrarVendedor' }).
jqGrid('inlineNav', '#vendedoresPager',
{
add : true,
edit : true,
save : true,
addParams: {
addRowParams: {
position: "afterSelected",
keys: true,
extraparam: {
...
}
}
},
editParams: {
keys: true,
extraparam: {
...
}
}
});
When adding the first row no default data, but then fields Vendedor, Especie, Guías Venta and Vencimiento should repeat the last entered.
In this scenario I imagine two possible solutions, one is using the event jqGridInlineEditRow, and the other is using autocomplete.
Have read this Question about qGridInlineEditRow. But in this case as I can get the data from the last row of the grid and how it should load the data into the new row.
And read this Question about autocomplete.
Maybe there other solutions that can read to get a better approximation to the solution.
Can anyone help?
update 15/04/2013
i replace the Add button for a custom button this is the code:
$("#Agregar").click(function () {
var parameters =
{
initdata: {},
position: "first",
useDefValues: true,
useFormatter: false,
addRowParams: {
keys: true,
extraparam: {
...
},
aftersavefunc: function (rowid) {
var grid = jQuery('#vendedores');
lastSavedAddData = grid.jqGrid("getRowData", rowid);
},
oneditfunc: function (rowid) {
var name;
var grid = jQuery('#vendedores');
for (name in lastSavedAddData) {
if (lastSavedAddData.hasOwnProperty(name)) {
$('#' + rowid +"_"+ name).val(lastSavedAddData[name]);
}
}
}
}
};
jQuery("#vendedores").jqGrid('addRow', parameters);
});
But this work only for text box but not for a combo
If I understand correctly your question the usage of jQuery UI Autocomplete is independent from initial filling of the input fields of the last added line during starting the next like to add.
It seems to me that you can save data saved in the last added line inside of aftersavefunc callback defined in addRowParams (or use jqGridInlineAfterSaveRow event alternatively). You can use oneditfunc to set the last entered values in the new like. For example you can use
addRowParams: {
position: "afterSelected",
keys: true,
extraparam: {
...
},
aftersavefunc: function (rowid) {
lastSavedAddData = $(this).jqGrid("getRowData", rowid);
},
oneditfunc: function (rowid) {
var name;
for (name in lastSavedAddData) {
if (lastSavedAddData.hasOwnProperty(name)) {
$("#" + $.jgrid.jqID(rowid + "_" + name)).val(lastSavedAddData[name]);
}
}
}
}
where lastSavedAddData should be defined in some outer scope. It's not tested code. I just wanted to show the main idea. You can extend the code of oneditfunc to support more different controls which you use in editing line.

Categories

Resources