First time JQGrid does not fire reload event - jqgrid

I have multiple grids in a page which are shown based on a drop down selection. The first time when the page is loaded and I select another grid name in the drop down that grid's data reload event is not fired but subsequent events fire properly. Can someone let me know what is the problem with first time event not getting fired?
The flow of the execution is as follows
On the page load all the grids numbered 2 to 4 are initialized without any URL. And grid 1 is loaded with data and shown to the user.
Also on page load other grid divs are hidden.
When a user selects any other grid name in the drop down that grids div is shown and a reload event is fired to load data with URL.
HTML code
<select id="gridType" onchange="javascript:onChangeGridType();">
<option value="1" selected="selected">Grid 1</option>
<option value="2">Grid 2</option>
<option value="3">Grid 3</option>
<option value="4">Grid 4</option>
</select>
<div id="grid1Div">
<table id="grid1">
<tr>
<td />
</tr>
</table>
<div id="pager1"></div>
</div>
<div id="grid2Div">
<table id="grid2">
<tr>
<td />
</tr>
</table>
<div id="pager2"></div>
</div>
<div id="grid3Div">
<table id="grid3">
<tr>
<td />
</tr>
</table>
<div id="pager3"></div>
</div>
<div id="grid4Div">
<table id="grid4">
<tr>
<td />
</tr>
</table>
<div id="pager4"></div>
</div>
Grid 1 initialization code
$("#grid1").jqGrid({
url: grid1URL,
datatype: 'json',
mtype: 'GET',
colNames:['column1',
'column2',
'column3'
],
colModel:[
{name:'col1',index:'col2',
width:140,sortable:true,editable:true},
{name:'col2',index:'col2',
width:120,sortable:true,editable:true},
{name:'col3',index:'col3',
width:160,sortable:true,editable:true}
],
pager: '#pager1',
paging:true,
rowNum:perPageRecords,
height:'auto',
loadonce: true,
sortorder: 'desc',
sortname:'col2',
viewrecords: true,
caption: 'Grid 1',
gridview:true,
width:'100%',
autowidth:true,
pginput:true,
ignoreCase:true,
shrinkToFit:false
});
$("#grid1").jqGrid('navGrid',"#pager1",{add:false, edit:false, del:false, search:true, refresh:true,
beforeRefresh: function(){....}},{},{},{},{});
Grid 2 initialization code
$("#grid2").jqGrid({
url: "",
datatype: 'json',
mtype: 'GET',
colNames:['column1',
'column2',
'column3'
],
colModel:[
{name:'col1',index:'col2',
width:140,sortable:true,editable:true},
{name:'col2',index:'col2',
width:120,sortable:true,editable:true},
{name:'col3',index:'col3',
width:160,sortable:true,editable:true}
],
pager: '#pager2',
paging:true,
rowNum:perPageRecords,
height:'auto',
loadonce: true,
sortorder: 'desc',
sortname:'col2',
viewrecords: true,
caption: 'Grid 2',
gridview:true,
width:'100%',
autowidth:true,
pginput:true,
ignoreCase:true,
shrinkToFit:false
});
$("#grid2").jqGrid('navGrid',"#pager2",{add:false, edit:false, del:false, search:true, refresh:true,
beforeRefresh: function(){....}},{},{},{},{});
Grid 3 initialization code
$("#grid3").jqGrid({
url: "",
datatype: 'json',
mtype: 'GET',
colNames:['column1',
'column2',
'column3'
],
colModel:[
{name:'col1',index:'col2',
width:140,sortable:true,editable:true},
{name:'col2',index:'col2',
width:120,sortable:true,editable:true},
{name:'col3',index:'col3',
width:160,sortable:true,editable:true}
],
pager: '#pager3',
paging:true,
rowNum:perPageRecords,
height:'auto',
loadonce: true,
sortorder: 'desc',
sortname:'col2',
viewrecords: true,
caption: 'Grid 3',
gridview:true,
width:'100%',
autowidth:true,
pginput:true,
ignoreCase:true,
shrinkToFit:false
});
$("#grid3").jqGrid('navGrid',"#pager3",{add:false, edit:false, del:false, search:true, refresh:true,
beforeRefresh: function(){....}},{},{},{},{});
Grid 4 initialization code
$("#grid4").jqGrid({
url: "",
datatype: 'json',
mtype: 'GET',
colNames:['column1',
'column2',
'column3'
],
colModel:[
{name:'col1',index:'col2',
width:140,sortable:true,editable:true},
{name:'col2',index:'col2',
width:120,sortable:true,editable:true},
{name:'col3',index:'col3',
width:160,sortable:true,editable:true}
],
pager: '#pager4',
paging:true,
rowNum:perPageRecords,
height:'auto',
loadonce: true,
sortorder: 'desc',
sortname:'col2',
viewrecords: true,
caption: 'Grid 4',
gridview:true,
width:'100%',
autowidth:true,
pginput:true,
ignoreCase:true,
shrinkToFit:false
});
$("#grid4").jqGrid('navGrid',"#pager4",{add:false, edit:false, del:false, search:true, refresh:true,
beforeRefresh: function(){....}},{},{},{},{});
onChangeGridType function
function onChangeGridType(){
var type = $("#gridType").val();
if (type == 1){
reloadGrid1();
$("#grid1Div").show();
$("#grid2Div").hide();
$("#grid3Div").hide();
$("#grid4Div").hide();
$("#grid1Div").css("visibility", "visible");
$("#grid2Div").css("visibility", "hidden");
$("#grid3Div").css("visibility", "hidden");
$("#grid4Div").css("visibility", "hidden");
} else if (type == 2){
reloadGrid2();
$("#grid1Div").hide();
$("#grid2Div").show();
$("#grid3Div").hide();
$("#grid4Div").hide();
$("#grid1Div").css("visibility", "hidden");
$("#grid2Div").css("visibility", "visible");
$("#grid3Div").css("visibility", "hidden");
$("#grid4Div").css("visibility", "hidden");
} else if (type == 3){
reloadGrid3();
$("#grid1Div").hide();
$("#grid2Div").hide();
$("#grid3Div").show();
$("#grid4Div").hide();
$("#grid1Div").css("visibility", "hidden");
$("#grid2Div").css("visibility", "hidden");
$("#grid3Div").css("visibility", "visible");
$("#grid4Div").css("visibility", "hidden");
} else if (type == 4) {
reloadGrid4();
$("#grid1Div").hide();
$("#grid2Div").hide();
$("#grid3Div").hide();
$("#grid4Div").show();
$("#grid1Div").css("visibility", "hidden");
$("#grid2Div").css("visibility", "hidden");
$("#grid3Div").css("visibility", "hidden");
$("#grid4Div").css("visibility", "visible");
}
}
'reload functions`
function reloadGrid1() {
$("#grid1").jqGrid('setGridParam',{datatype : 'json',url : grid1URL}).trigger('reloadGrid', [ {page : 1} ]);
}
function reloadGrid2() {
$("#grid2").jqGrid('setGridParam',{datatype : 'json',url : grid2URL}).trigger('reloadGrid', [ {page : 1} ]);
}
function reloadGrid3() {
$("#grid3").jqGrid('setGridParam',{datatype : 'json',url : grid3URL}).trigger('reloadGrid', [ {page : 1} ]);
}
function reloadGrid4() {
$("#grid4").jqGrid('setGridParam',{datatype : 'json',url : grid4URL}).trigger('reloadGrid', [ {page : 1} ]);
}

For other grids I changed the grid URL value to empty and datatype as "local" that did the trick.

Related

Datatable on change ajax on checkbox not working

Datatable on change ajax on checkbox not working, I have a data table and i am trying to update the value of active in the table into 1 if the checkbox is clicked, and 0 if clicked again. It is not even displaying the console log that i have inserted, I do not where to start. Thank you in advance for any help
ShopsController:
public function activeswitch(){
DB::table('shops')
->update(['active'=>1]);
}
blade.php:
<script>
$(document).ready(function () {
table = $('#shops_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{url('api/admin/shops/get-shops')}}",
rowId: "id",
stateSave: true,
dom: 'Bfrtip',
"buttons": [
'excelHtml5',
'pdf',
'print'
],
"order": [[ 0, "desc" ]],
columns: [
{data: 'id'},
{data: 'name'},
{data: 'image', render: function(data){
return "<img src='/storage/uploads/logo/" + data + "' width=auto height='50' />"
}},
{data: 'color'},
{data: 'switch', render: function(data){
return '<label class="switch">' +
' <input type="checkbox" class="checkbox">' +
'<span class="slider round" data-active-value=0>' +
' </span>' +
' </label>';
}},
{data: 'id', 'width' : '10%', render: function(data){
return '<div class="action-buttons">' +
'<i class="fa fa-eye"></i>' +
'<i class="fa fa-pencil"></i>' +
' <form action="shops/'+data+'" method="POST" style="display: inline-block;">' +
'<input type="hidden" name="_method" value="DELETE" />' +
' #csrf' +
'<button class="btn btn-xs btn-rounded btn-danger" type="submit"><i class="fa fa-trash"></i></button>' +
' </form>' +
'</div>';
}}
],
});
});
$( document ).ready(function() {
$(".checkbox").change(function(e){
console.log('hi')
e.preventDefault();
var selct_ = $(this) //declare this
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('active.switch') }}",
data:{
'active':$(this).data('active-value')
},
type: "get",
success: function(result){
console.log('hi')
}
});
});
});
</script>
It's not working because you're adding listeners to elements that don't exists yet.
Datatables.js has a callback that runs once it's been drawn, try this:
$(document).ready(function () {
table = $('#shops_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{url('api/admin/shops/get-shops')}}",
rowId: "id",
stateSave: true,
dom: 'Bfrtip',
"buttons": [
'excelHtml5',
'pdf',
'print'
],
"order": [[ 0, "desc" ]],
columns: [
{data: 'id'},
{data: 'name'},
{data: 'image', render: function(data){
return "<img src='/storage/uploads/logo/" + data + "' width=auto height='50' />"
}},
{data: 'color'},
{data: 'switch', render: function(data){
return '<label class="switch">' +
' <input type="checkbox" class="checkbox">' +
'<span class="slider round" data-active-value=0>' +
' </span>' +
' </label>';
}},
{data: 'id', 'width' : '10%', render: function(data){
return '<div class="action-buttons">' +
'<i class="fa fa-eye"></i>' +
'<i class="fa fa-pencil"></i>' +
' <form action="shops/'+data+'" method="POST" style="display: inline-block;">' +
'<input type="hidden" name="_method" value="DELETE" />' +
' #csrf' +
'<button class="btn btn-xs btn-rounded btn-danger" type="submit"><i class="fa fa-trash"></i></button>' +
' </form>' +
'</div>';
}}
],
"fnDrawCallback": function() {
$(".checkbox").change(function (e) {
console.log('hi')
});
}
});
});

pager function not work well while multi grid in one page

Thank you about open source the jqgrid.
I got a pager problem about multi grid in one page.
There are first grid (eg. contactGrid) and the rest grids(eg. orderGrid) in one page, and contactGrid on top, the rest listed on bottom.
The function of contactGrid is great, but the pager function of rest grids are not work well.
Some times after the page initialized, some of the rest grids did
not show the data requested from server.
It do show nothing while I
click next page, last page, or change the page size on each of the
rest grids.
I check the network on firefox, it showed the request url like this:
http://127.0.0.1:8080/hx-customer/saleProblem/bizsaleproblem/list?delFlag=0&customerId=632&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&_=1524161697902
And after the page and all grids initialized, the console.dir(ts.p.postData) I added in jqgrid source showed like this:
after the page and all grids initialized
I'm using the last version of v5.3.1, jquery version is v2.2.4.
Here are my source code:
var custId,_userName,_contacts,_email,$contactsGrid,$followGrid,$orderGrid,$saleGrid, v, commonParam = '';
$(function () {
vm.loadDict();
handleParam();
custId = localStorage.getItem("addCust#custId");
if (custId) {
localStorage.removeItem("addCust#custId");
commonParam = '&customerId='+custId;
vm.getInfo(custId);
} else {
findUser();
}
$("#contactsGrid").jqGrid({
url: baseURL + 'contact/bizcustomercontact/list?delFlag=0'+commonParam,
datatype: "json",
colModel: [
{label: 'id', name: 'customerContactId', index: 'customer_contact_id', key: true, hidden: true },
{label: '序号', name: 'customerId', index: 'customer_id', hidden: true},
{label: '联系人', name: 'contacts', index: 'contacts', width: 80},
],
viewrecords: true,
height: 200,
rowNum: 10,
rowList: [2,10, 30, 50],
rownumbers: true,
rownumWidth: 25,
autowidth: true,
multiselect: true,
pager: "#contactsGridPager",
jsonReader: {
root: "contactPage.list",
page: "contactPage.currPage",
total: "contactPage.totalPage",
records: "contactPage.totalCount"
},
prmNames: {
page: "page",
rows: "limit",
order: "order"
},
beforeRequest: function () {
console.dir('contact request', $("#contactsGrid").jqGrid('getGridParam','postData'));
},
gridComplete: function () {
//隐藏grid底部滚动条
$("#contactsGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
}
});
$("#followGrid").jqGrid({
url: baseURL + 'follow/bizfollow/list?delFlag=0'+commonParam,
datatype: "json",
colModel: [
{label: 'id', name: 'followId', index: 'follow_id', width: 50, key: true, hidden: true },
{label: '序号', name: 'customerId', index: 'customer_id', width: 80, hidden: true},
{label: '邮件日期', name: 'mailDate', index: 'mail_date', width: 80},
],
viewrecords: true,
height: 200,
rowNum: 10,
rowList: [2,10, 30, 50],
rownumbers: true,
rownumWidth: 25,
autowidth: true,
multiselect: true,
pager: "#followGridPager",
jsonReader: {
root: "followPage.list",
page: "followPage.currPage",
total: "followPage.totalPage",
records: "followPage.totalCount"
},
prmNames: {
page: "page",
rows: "limit",
order: "order"
},
beforeRequest: function () {
console.dir('follow request', $("#followGrid").jqGrid('getGridParam','postData'));
},
gridComplete: function () {
//隐藏grid底部滚动条
$("#followGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
}
});
$("#orderGrid").jqGrid({
url: baseURL + 'order/bizorder/list?delFlag=0'+commonParam,
datatype: "json",
colModel: [
{label: 'orderId', name: 'orderId', index: 'order_id', width: 50, key: true, hidden: true },
{label: '订单日期', name: 'orderDate', index: 'order_date', width: 80},
],
viewrecords: true,
height: 200,
rowNum: 10,
rowList: [2,10, 30, 50],
rownumbers: true,
rownumWidth: 25,
autowidth: true,
multiselect: true,
pager: "#orderGridPager",
jsonReader: {
root: "orderPage.list",
page: "orderPage.currPage",
total: "orderPage.totalPage",
records: "orderPage.totalCount"
},
prmNames: {
page: "page",
rows: "limit",
order: "order"
},
beforeRequest: function () {
console.dir('order request', $("#orderGrid").jqGrid('getGridParam','postData'));
},
gridComplete: function () {
//隐藏grid底部滚动条
$("#orderGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
}
});
$("#saleGrid").jqGrid({
url: baseURL + 'saleProblem/bizsaleproblem/list?delFlag=0'+commonParam,
datatype: "json",
colModel: [
{label: 'id', name: 'saleProblemId', index: 'sale_problem_id', width: 50, key: true, hidden: true },
{label: '反馈日期', name: 'feedbackDate', index: 'feedback_date', width: 80},
],
viewrecords: true,
height: 200,
rowNum: 10,
rowList: [2,10, 30, 50],
rownumbers: true,
rownumWidth: 25,
autowidth: true,
multiselect: true,
pager: "#saleGridPager",
jsonReader: {
root: "salePage.list",
page: "salePage.currPage",
total: "salePage.totalPage",
records: "salePage.totalCount"
},
prmNames: {
page: "page",
rows: "limit",
order: "order"
},
beforeRequest: function () {
console.dir('sale request', $("#saleGrid").jqGrid('getGridParam','postData'));
},
gridComplete: function () {
//隐藏grid底部滚动条
$("#saleGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
}
});
});
<!DOCTYPE html>
<html>
<head>
<title>客户清单表</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="../../css/font-awesome.min.css">
<link rel="stylesheet" href="../../plugins/jqgrid/ui.jqgrid-bootstrap.css">
<link rel="stylesheet" href="../../css/main.css">
<link rel="stylesheet" href="../../css/bootstrap.min.css">
<link rel="stylesheet" href="../../css/customer.css">
<script src="../../libs/jquery.js"></script>
<script src="../../plugins/layer/layer.js"></script>
<script src="../../libs/bootstrap.min.js"></script>
<script src="../../libs/vue.min.js"></script>
<script src="../../plugins/jqgrid/grid.locale-cn.js"></script>
<script src="../../plugins/jqgrid/jquery.jqGrid.js"></script>
<script src="../../js/common.js"></script>
</head>
<body>
<div id="rrapp" v-cloak>
<div v-show="showDivTitles" class="panel-heading item-title">客户档案-联系人
<div class="model-toggle" #click="modelSwitch('showDivContacts')">
<i class="fa " :class="{ 'fa-caret-square-o-up': showDivContacts, 'fa-caret-square-o-down': !showDivContacts }" aria-hidden="true"></i>
</div>
</div>
<div v-show="showDivContacts" id="contactsDiv">
<div v-show="showContacts">
<table id="contactsGrid"></table>
<div id="contactsGridPager"></div>
</div>
</div>
<div v-show="showDivTitles" class="panel-heading item-title">客户档案-跟进记录
<div class="model-toggle" #click="modelSwitch('showDivFollow')">
<i class="fa " :class="{ 'fa-caret-square-o-up': showDivFollow, 'fa-caret-square-o-down': !showDivFollow }" aria-hidden="true"></i>
</div>
</div>
<div v-show="showDivFollow" id="followDiv">
<div v-show="showFollow">
<table id="followGrid"></table>
<div id="followGridPager"></div>
</div>
</div>
<div v-show="showDivTitles" class="panel-heading item-title">客户档案-订单交易
<div class="model-toggle" #click="modelSwitch('showDivOrder')">
<i class="fa " :class="{ 'fa-caret-square-o-up': showDivOrder, 'fa-caret-square-o-down': !showDivOrder }" aria-hidden="true"></i>
</div>
</div>
<div v-show="showDivOrder" id="orderDiv">
<div v-show="showOrder">
<table id="orderGrid"></table>
<div id="orderGridPager"></div>
</div>
</div>
<div v-show="showDivTitles" class="panel-heading item-title">客户档案-售后记录
<div class="model-toggle" #click="modelSwitch('showDivSale')">
<i class="fa " :class="{ 'fa-caret-square-o-up': showDivSale, 'fa-caret-square-o-down': !showDivSale }" aria-hidden="true"></i>
</div>
</div>
<div v-show="showDivSale" id="saleDiv">
<div v-show="showSale">
<table id="saleGrid"></table>
<div id="saleGridPager"></div>
</div>
</div>
<div v-show="showDivTitles" class="row">
<div class="common-btn-ground">
<!--<button type="button" class="btn btn-info common-btn" #click="save">保存</button>-->
<button type="button" class="btn btn-info common-btn" #click="back"><!-- onclick="history.go(-1)" -->
<i class="fa fa-rotate-left"></i>&nbsp返回</button>
</div>
</div>
</div>
<script src="../../js/modules/customer/addCustFile.js"></script>
</body>
</html>

MVC3 jqGrid subgrid using subGridrowExpanded

I'm developing an MVC3/razor application, and I am trying to use the subGridRowExpanded to nest a jqGrid inside another (so I can use the formatter amongst other things), how do i pass the id value Of the parent Grid to the Child grid?
The below code runs the main grid, and populates it with Data from the "Search/Customers" URL, but I do not know how to select the record I've Selected in the 'Search/BankLinks' URL controller
Can anyone tell me how to do this?
Thanks in advance
Andrew.
My Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>#ViewBag.Message</h2>
<div id="content">
<div id="content-left">
#Html.Partial("SearchPanel")
</div>
<div id="content-main">
<table id="jpgCustomers" cellpadding="0" cellspacing="0"></table>
<div id="jpgpCustomers" style="text-align:center;"></div>
</div>
</div>
#section JavaScript
{
<script type="text/javascript">
$(document).ready(function ()
{
$('#jpgCustomers').jqGrid({
//url from wich data should be requested
url: '#Url.Action("Customers")',
datatype: 'json',
mtype: 'POST',
colNames: ['Name', 'FullName', 'SFTP Enabled', 'IsTranbase'],
colModel: [
{ name: 'LogonName', index: 'LogonName', align: 'left' },
{ name: 'FullName', index: 'FullName', align: 'left' },
{ name: 'Enabled', index: 'Enabled', align: 'left' },
{ name: 'IsTran', index: 'IsTranbase', align: 'left' }
],
pager: $('#jpgpCustomers'),
rowNum: 10,
sortname: 'FullName',
sortorder: 'asc',
viewrecords: true,
height: '100%',
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"'class='scroll'></table><div id='"+pager_id+"'class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url: '#Url.Action("BankLinks")',
datatype: 'json',
mtype: 'POST',
colNames: ['Bank', 'Folder', 'Enabled'],
colModel:[
{name:"Bank",index:"Bank",width:80,key:true},
{name:"Folder",index:"Folder",width:130},
{name:"Enabled",index:"Enabled",width:70,align:"left"}
],
rowNum:20,
pager: pager_id,
sortname: 'Bank',
sortorder: "asc",
viewrecords: true,
height: '100%'
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:false,del:false})
},
});
});
</script>
}
My Controller Actions:
Customers
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Customers(JqGridRequest request)
{
ISession session = NHibernateHelper.GetCurrentSession();
IEnumerable<Customer> customers = session.QueryOver<Customer>().List().Skip<Customer>(0).Take<Customer>(request.RecordsCount);
int totalRecords = customers.Count();
//Prepare JqGridData instance
JqGridResponse response = new JqGridResponse()
{
//Total pages count
TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
//Page number
PageIndex = request.PageIndex,
//Total records count
TotalRecordsCount = totalRecords
};
//Table with rows data
foreach (Customer customer in customers)
{
response.Records.Add(new JqGridRecord(Convert.ToString(customer.Id), new List<object>()
{
customer.FtpDetails.LogonName,
customer.FtpDetails.FullName,
customer.FtpDetails.Enabled,
customer.IsTran
}));
}
//Return data as json
return new JqGridJsonResult() { Data = response };
}
BankLinks
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BankLinks(JqGridRequest request)
{
ISession session = NHibernateHelper.GetCurrentSession();
//IN THIS LINE I HAVE HARDCODED value 14 - I need this value to be passed from the
//Parent Grid!
Customer customer = session.Get<Customer>(14);
int totalRecords = customer.Banks.Count();
//Prepare JqGridData instance
JqGridResponse response = new JqGridResponse()
{
//Total pages count
TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
//Page number
PageIndex = request.PageIndex,
//Total records count
TotalRecordsCount = totalRecords
};
foreach (Bank bank in customer.Banks.ToList<Bank>())
{
CustomerBank bankLink = session.QueryOver<CustomerBank>().Where(x => x.BankId == bank.Id).Where(y => y.CustomerId == customer.Id).List<CustomerBank>().FirstOrDefault();
response.Records.Add(new JqGridRecord(null, new List<object>()
{
bank.BankCode,
bank.Folder,
bankLink.Enabled
}));
}
return new JqGridJsonResult() { Data = response };
}
First you should modify your subGridRowExpanded callback like this:
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + '_t';
pager_id = "p_"+subgrid_table_id;
$('#' + subgrid_id).html('<table id="' + subgrid_table_id + '" class="scroll"></table><div id="' + pager_id + '" class="scroll"></div>');
$('#' + subgrid_table_id).jqGrid({
url: encodeURI('#Url.Action("BankLinks")' + '?id=' + row_id),
datatype: 'json',
mtype: 'POST',
colNames: ['Bank', 'Folder', 'Enabled'],
colModel: [
{name: 'Bank', index: 'Bank', width:80, key:true },
{name: 'Folder', index:'Folder', width:130 },
{name: 'Enabled', index: 'Enabled', width:70, align: 'left' }
],
rowNum: 20,
pager: pager_id,
sortname: 'Bank',
sortorder: 'asc',
viewrecords: true,
height: '100%'
});
$('#' + subgrid_table_id).jqGrid('navGrid', '#' + pager_id, {edit: false, add: false, del: false })
}
Notice the usage of encodeURI in order to make sure that the produced URL is valid.
Now you can modify your action method like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BankLinks(int id, JqGridRequest request)
{
//You can sue id parameter to get the data for selected client.
...
}
This should do the trick.

Custom template column does not work in JQGrid

Experts,
I have JQGrid with custom template column like Edit. the following screen display data without Edit link in last column.
Javascript code:
<script language="javascript" type="text/javascript">
function editFmatter(cellvalue, options, rowObject) {
var cellHtml = "<a href='#' originalValue='" + cellvalue + "'>" + cellvalue + "</a>";
return cellHtml;
}
function unformatEdit(cellvalue, options) {
return $(cellObject.html()).attr("originalValue");
}
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("JQGridGetGridData", "TabMaster")',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name', 'Edit'],
colModel: [
{ name: 'colID', index: 'colID', width: 100, align: 'left', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{ name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
{ name: 'LastName', index: 'LastName', width: 150, align: 'left', editable: true },
{ name: 'Edit', index: 'Edit', width: 80, align: "center", editable: true, formatter: editFmatter, unformat: unformatEdit }
],
pager: jQuery('#pager'),
rowNum: 100,
rowList: [10, 50, 100, 150],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
multiselect: true,
imgpath: '#Url.Content("~/Scripts/themes/steel/images")',
caption: 'Tab Master Information'
}).navGrid('#pager', { edit: true, add: true, del: true },
// Edit options
{
savekey: [true, 13],
reloadAfterSubmit: true,
jqModal: false,
closeOnEscape: true,
closeAfterEdit: true,
url: '#Url.Action("JQGridEdit", "TabMaster")',
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Record updated successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Add options
{
url: '#Url.Action("JQGridCreate", "TabMaster")',
closeAfterAdd: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Record added successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Delete options
{
url: '#Url.Action("JQGridRemove", "TabMaster")',
afterSubmit: function (response, rowid) {
if (rowid.length > 0) {
jQuery("#success").show();
jQuery("#success").html("Record deleted successfully! [" + rowid + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
{
closeOnEscape: true,
multipleSearch: false,
closeAfterSearch: true
}
);
});
</script>
#using (Html.BeginForm())
{
<p>
#Html.ActionLink("Create New", "Create") | #Html.ActionLink("Bulk Insert", "AddList")
#* | #Html.ActionLink((string)ViewBag.RemoveSelectedTitle, "RemoveSelected")*#
</p>
<table id="list" class="scroll" cellpadding="0" cellspacing="0" width="100%">
</table>
<div id="pager" class="scroll" style="text-align: center;">
</div>
<div id="success" style="color: Green">
</div>
Controller.cs
public JsonResult JQGridGetGridData(string sidx, string sord, int rows, int page)
{
int totalRecords = Convert.ToInt32(_tabmasterService.Count());
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(sidx, sord, rows, page);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from tm in tabmasters
select new
{
id = tm.colID,
cell = new string[] { tm.colID.ToString(), tm.FirstName, tm.LastName, "Edit" }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
First of all I would recommend you to take a look in this and this answers which shows how you can implement Edit links in the jqGrid.
Your current code have some problems:
In the unformatEdit you forgot to define the third parameter cellObject and use undefined value.
It's not good to add attributes like originalValue which are not corresponds to HTML standards. If you do need to extend attributes you should use data- prefix in the attribute name to be HTML5 compliant. In the case you can change the code to $(cellObject).children('a:first').attr("data-originalValue"); for example.
It is not good to define global functions because of possible name conflicts. You can move declaration of the function inside of jQuery(document).ready(function () {/*here*/}); event handler. You can define the function like a variables: var editFmatter = function(cellvalue, options, rowObject) {/* the body of the function*/}; and use later in the same way like you did as before.
You should use the last version of jqGrid (currently 4.1.1). Many parameters like imgpath which you use are not exist since years (see here). If you look for more recent ASP.NET MVC code example I would recommend you take a look in the "UPDATED" part of the answer and download the corresponding code examples (the VS2008 project and the VS2010 project).
I have solved question from myself.
I have done following:
{ name: 'Edit', index: 'Edit', width: 80, align: 'center', editable: false, formatter: editFmatter, unformat: unformatEdit }
and
function editFmatter(el, cellval, opts) {
var editHTML = "<img src='Images/row_edit.gif' alt='Edit' title='Edit' onclick='openEditDialog(" + opts.rowId + ");'>";
var deleteHTML = "<img src='Images/row_delete.gif' alt='Delete' title='Delete' onclick='openDeleteDialog(" + opts.rowId + ");'>"; ;
var finalHTML = editHTML + " " + deleteHTML;
$(el).html(finalHTML);
}
function unformatEdit(cellvalue, options) {
//return $(el).html().attr("originalValue");
}
Thanks,
Imdadhusen

jqgrid tooltip for header cells only

How can i add tooltip to my jqgrid header cells? in case of multiple grids in the same page.
This is my code:
var initialized = [false,false,false];
$('#tabs').tabs
(
{
show: function(event, ui)
{
if(ui.index == 0 && !initialized[0])
{
init_confirm_payment();
initialized[0] = true;
}
else if(ui.index == 1 && !initialized[1])
{
init_signatory1_payment();
initialized[1] = true;
}
else if(ui.index == 2 && !initialized[2])
{
init_signatory2_payment();
initialized[2] = true;
}
}
}
);
function init_table1()
{
jQuery("#cpayment").jqGrid({
url:'loadgrid.jsp?type=1',
datatype: "xml",
loadonce:true ,
direction:"rtl",
height: '100%',
width: '100%',
headertitles: true ,
colNames:['col11','col22','col33','col44'],
colModel:[
{name:'col11',xmlmap:'col11', width:80, align:"right",sorttype:"int"},
{name:'col22',xmlmap:'col22', width:70, align:"right",sorttype:"int"},
{name:'col33',xmlmap:'col33', width:120, align:"right",sorttype:"string"},
{name:'col44:'col44', width:60, align:"right",sorttype:"float"},
],
multiselect: false,
autowidth: true,
forceFit: false,
shrinkToFit: false,
loadonce:true
});
}
function init_table2()
{
jQuery("#payment1").jqGrid({
url:'loadgrid.jsp?type=2',
datatype: "xml",
direction:"rtl",
height: '100%',
width: '100%',
headertitles: true ,
colNames:['col111','col222','col333','col444'],
colModel:[
{name:'col111',xmlmap:'col111', width:80, align:"right",sorttype:"int"},
{name:'col222',xmlmap:'col222', width:70, align:"right",sorttype:"int"},
{name:'col333',xmlmap:'col333', width:120, align:"right",sorttype:"string"},
{name:'col444',xmlmap:'col444', width:60, align:"right",sorttype:"float"},
],
multiselect: false,
autowidth: true,
forceFit: false,
shrinkToFit: false,
loadonce:true
});
}
function init_table3()
{
jQuery("#payment2").jqGrid({
url:'loadgrid.jsp?type=3',
datatype: "xml",
direction:"rtl",
height: '100%',
width: '100%',
headertitles: true ,
colNames:['col1','col2','col3','col4'],
colModel:[
{name:'col1',xmlmap:'col1', width:80, align:"right",sorttype:"int"},
{name:'col2',xmlmap:'col2', width:70, align:"right",sorttype:"int"},
{name:'col3',xmlmap:'col3', width:120, align:"right",sorttype:"string"},
{name:'col4xmlmap:'col4', width:60, align:"right",sorttype:"float"},
],
multiselect: false,
autowidth: true,
forceFit: false,
shrinkToFit: false,
loadonce:true
});
}
function test()
{
var thd = jQuery("thead:first", $("#cpayment").hdiv)[0];
jQuery("tr th:eq(" + 3 + ")", thd).attr("title", "bla bla");
var thd1 = jQuery("thead:first", $("#payment1").hdiv)[0];
jQuery("tr th:eq(" + 3 + ")", thd1).attr("title", "bla bla1");
}
</script>
</head>
<body>
<form>
<div id="tabs">
<ul>
<li> tab1 </li>
<li> tab2 </li>
<li> tab3 </li>
</ul>
<div id="tabs-1">
<table id="cpayment"></table>
</div>
<div id="tabs-2">
<table id="payment1"></table>
</div>
<div id="tabs-3">
<table id="payment2"></table>
</div>
</div>
<input type="button" onClick="test()">
</form>
</body>
Thank's In Advance.
Just include headertitles:true option in your jqGrid definition.
UPDATED: If you want set custom tooltip on a column header you can do following:
var setTooltipsOnColumnHeader = function (grid, iColumn, text) {
var thd = jQuery("thead:first", grid[0].grid.hDiv)[0];
jQuery("tr.ui-jqgrid-labels th:eq(" + iColumn + ")", thd).attr("title", text);
};
setTooltipsOnColumnHeader($("#list"), 1, "bla bla");
You should take in the consideration, that the column number iColumn is the 0-based absolute index of the column. Every from the options rownumbers:true, multiselect:true or subGrid:true include an additional column at the beginning, so the corresponding iColumn index should be increased.
UPDATED 2: For more information about the structure of dives, internal grid.hDiv elements and the classes used by jqGrid see this answer.
In my case I don't have index of the column to which I would like to set the tooltip.
I have modified the above answer by #Oleg as below.
//grid object, column id, tooltip text
var setTooltipsOnColumnHeader = function (grid, iColumn, text) {
var thd = jQuery("thead:first", grid[0].grid.hDiv)[0];
jQuery("tr.ui-jqgrid-labels", thd).find("[id='"+iColumn+"']").attr("title",text);
};
To add tooltip just call this methode on loadcomplete:
addToolTipForColumnheader('YourGridID');
function addToolTipForColumnheader(gridID){
var columnNameList=$('#'+gridID)[0].p.colNames;
for (var i = 0; i < columnNameList.length; i++){
var columnName=$('#'+gridID)[0].p.colModel[i].name;
$('#'+gridID+'_'+columnName).attr("title", $('#'+gridID)[0].p.colNames[i]);
}
}

Resources