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
Related
I have following code using free-jqgrid. It loads correctly for the first time (Status is “Active” and Partner? is “Yes”). But when I do a sort or search, the values become incorrect(Status is “Retired” and Partner? is “No”).
Why the formatters are giving incorrect values? How to fix this?
SCRIPT
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/start/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/js/jquery.jqgrid.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/css/ui.jqgrid.min.css" rel="stylesheet" />
<script type="text/javascript">
function getCurrentPractice ()
{
return "Test";
}
function getGridCaption() {
return "<div style='font-size:15px; font-weight:bold; display:inline; padding-left:10px;'><span class='glyphicon glyphicon-check' style='margin-right:3px;font-size:14px;'></span>" + getCurrentPractice() + " " + "</div>" +
"<div style='float:right; padding-right:20px; padding-bottom:10px; display:inline;>" +
"<div style='float:right;width:550px; padding-bottom:20px;'>" +
"<input type='text' class='form-control' id='filter' placeholder='Search' style='width:250px; height:30px; float:right; ' />" +
" </div>" +
"</div>";
}
$(function () {
var currentPractice = "P";
var grid = $("#list2");
grid.jqGrid({
url: '/Home/GetProviders',
datatype: "json",
postData:
{
practiceName: function () { return currentPractice }
},
colNames: [
'Practice',
'ProviderID',
'Partner?',
'Status'
],
colModel: [
{ name: 'Practice', hidden: false },
{ name: 'ProviderID', hidden: false },
{
name: 'PartnerStatusText',
width: 70,
formatter: function (cellvalue, options, rowObject) {
var isPartner = rowObject.IsPartner;
return isPartner == true ? 'Yes' : 'No';
}
},
{
name: 'ActiveStatusText',
width: 70,
formatter: function (cellvalue, options, rowObject) {
var isActive = rowObject.IsActive;
return isActive == true ? 'Active' : 'Retired';
}
}
],
ignoreCase: true,
loadonce: true,
rowNum: 25,
rowList: [15, 25, 35, 50],
pager: '#pager2',
viewrecords: true,
sortable: true,
caption: getGridCaption(),
beforeSelectRow: function (rowid, e) {
//Avoid selection of row
return false;
},
loadComplete: function () {
}
});
grid.jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false });
//Filter Toolbar
$("#advancedSearch").click(function () {
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
});
//Top Search
$("#filter").on('keyup', function () {
var searchFiler = $("#filter").val(), f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
}
f = { groupOp: "OR", rules: [] };
f.rules.push({ field: "Practice", op: "cn", data: searchFiler });
grid[0].p.search = true;
$.extend(grid[0].p.postData, { filters: JSON.stringify(f) });
grid.trigger("reloadGrid", [{ page: 1, current: true }]);
});
});
</script>
</head>
HTML
<div style="float:left; border:1px solid red;">
<div id="divGrid" style="width: 680px; min-height: 50px; float: left; border: 1px solid silver;">
<table id="list2"></table>
<div id="pager2"></div>
</div>
</div>
Server Code
[AllowAnonymous]
public JsonResult GetProviders(string practiceName)
{
//System.Threading.Thread.Sleep(3000);
List<Provider> providers = new List<Provider>();
Provider p = new Provider();
p.Practice = "Test1";
p.ProviderID = 1;
p.IsActive = true;
p.IsPartner = true;
providers.Add(p);
Provider p2 = new Provider();
p2.Practice = "Test2";
p2.ProviderID = 2;
p2.IsActive = true;
p2.IsPartner = true;
providers.Add(p2);
return Json(providers, JsonRequestBehavior.AllowGet);
}
UPDATE
Thanks to Oleg, working demo can be found here - Fiddle . It uses "/echo/json/" service of JSFiddle to get data from server.
It uses sorttype and additionalProperties. This can be rewritten without additionalProperties - I need to do it when I get a chance to revisit this.
The problem seems be very easy. The data returned from the server contains properties Practice, ProviderID, IsActive and IsPartner. The properties are available in rowObject during initial loading. You use additionally loadonce: true option. Thus free jqGrid will try to save some data locally, but which one? jqGrid saves by default the properties which corresponds the names of columns: Practice, ProviderID, PartnerStatusText and ActiveStatusText, but jqGrid have no information that other properties IsActive and IsPartner need be saved too.
You can solve the problem in two alternative ways:
you rename the column names PartnerStatusText and ActiveStatusText to IsActive and IsPartner.
you add the option additionalProperties: ["IsActive", "IsPartner"] to inform jqGrid to read and save locally additional properties.
Moreover, I'd recommend you to use options.rowData instead of rowObject inside of custom formatter. You can skip the 3-d parameter and to use formatter: function (cellvalue, options) {...}.
The final remark: the current code of the custom formatter is very easy. You need to replace some input values (true and false) to another text. One can use formatter: "select" for the case:
colModel: [
{ name: "Practice" },
{ name: "ProviderID" },
{
name: "IsPartner",
width: 70,
formatter: "select",
formatoptions: { value: "false:No;true:Yes" }
},
{
name: "IsActive",
width: 70,
formatter: "select",
formatoptions: { value: "false:Retired;true:Active" }
}
],
See https://jsfiddle.net/c9fge9yk/1/
i have loaded the following jqGrid grid in regards to car annual check up for maintenance data.
On chrome this looks like this:
This was generated as a react object, the code as follows:
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/start/jquery-ui.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/css/ui.jqgrid.min.css" />
</head>
<body>
<div id="divContainer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script src="https://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script>
<script type="text/babel" src="sample.jsx">
</script>
</body>
</html>
JSX code:
var SampleGrid = React.createClass({
componentDidMount:function(){
this.gridLoad();
},
gridLoad:function(){
var mydata = [
{ id: "1", test: "Engine checkup", teststart: "12/12/2016", testend: "12/30/2016", passed: true},
{ id: "2", test: "Electrical Checkup", teststart: "1/2/2017", testend: "1/3/2017", passed: false},
{ id: "3", test: "Chasis checkup", teststart: "1/4/2017", testend: "1/5/2017", passed: false},
{ id: "4", test: "Aerodynamics checkup", teststart: "1/6/2017", testend: "1/9/2017", passed: true},
{ id: "5", test: "Balance and stability checkup", teststart: "1/10/2017", testend: "1/12/2017", passed: true},
{ id: "6", test: "Report", teststart: "", testend: "", closed: false }
];
jQuery("#grid100").jqGrid({
colNames: ['test','passed','test started','test ended'],
colModel: [
{name: 'test', index: 'test', width: 220 },
{name: 'passed', index: 'passed', width: 60, align: 'center', formatter: 'checkbox',
edittype: 'checkbox', editoptions: {value: 'Yes:No', defaultValue: 'Yes'}, formatoptions: { disabled: false},
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' colspan="3"' }},
formatter:function(cellvalue, options, rowObject)
{
if(rowObject.id==6)
{
return '<input type="text" id="txtnotes" ref="refnotes" />';
}
else
{
if(rowObject.passed===true)
{
return '<input type="checkbox" id="cbPassed-'+ rowObject.id +'" checked/>';
}
else
{
return '<input type="checkbox" id="cbPassed-'+rowObject.id+ '" />';
}
}
}
},
{name: 'teststart', index: 'teststart', width: 75, formatter: 'string', sorttype: 'string', align: 'center',
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' style="display:none;"' }}},//return ' colspan="5"'
{name: 'testend', index: 'testend', width: 75, formatter: 'string', sorttype: 'string', align: 'center',
cellattr: function(rowId, tv, rawObject, cm, rdata) {
if (Number(rowId) == 6) { return ' style="display:none;"' }}}
],
rowNum: 10,
rowList: [5, 10, 20],
threeStateSort:true,
gridview: true,
rownumbers: false,
autoencode: true,
ignoreCase: true,
sortname: "id",
viewrecords: true,
sortorder: "desc",
shrinkToFit: false,
});
for(var i=0;i<=mydata.length;i++)
jQuery("#grid100").jqGrid('addRowData',i+1,mydata[i]);
jQuery("#grid100").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders:[
{startColumnName: 'passed', numberOfColumns: 3, titleText: 'Test Duration'}
]
});
},
render:function(){
return(<div id="gridContainer" ref="refContainer">
<form>
<table id="grid100"></table>
</form>
</div>
)
}
})
ReactDOM.render(<SampleGrid />, document.getElementById('divContainer'));
But this behaves funny. when i ran the code in chrome it works perfectly fine but when i ran this on IE (my version is 10) it gives the following error on console
SCRIPT1046: Multiple definitions of a property not allowed in strict mode
At the moment i cannot figure out why the same code produces results in one browser and not in another. But i know this error raised since i have added the formater to the column passed
formatter:function(cellvalue, options, rowObject)
{
if(rowObject.id==6)
{
return '<input type="text" id="txtnotes" ref="refnotes" />';
}
else
{
if(rowObject.passed===true)
{
return '<input type="checkbox" id="cbPassed-'+ rowObject.id +'" checked/>';
}
else
{
return '<input type="checkbox" id="cbPassed-'+rowObject.id+ '" />';
}
}
}
How do i fix this issue?
The reason of the problem: the usage of multiple formatter property for the column passed (see formatter: 'checkbox', ..., formatter:function(cellvalue, options, rowObject) {...}). You should remove or comment the formatter: 'checkbox' from your code.
I'd recommend you additionally:
never fill the grid with data using addRowData in the loop. You should remove the lines for(var i=0;i<=mydata.length;i++) jQuery("#grid100").jqGrid('addRowData',i+1, mydata[i]); from your code. Additionally you should add data: mydata parameter and to remove unneeded sortorder: "desc" option.
to remove all index properties from colModel
remove unneeded options gridview: true, rownumbers: false, ignoreCase: true. All the values are already defaults in free jqGrid.
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.
I've a datagrid to show employee particular but i need to set a logic where
if Role=Manager then show all the employee and if Role=Employee show only 1 data which belong to him. Below is my code to show the employee. I managed to show all employee. Need help to set filter for employee.
View
#model IEnumerable<SealManagementPortal_3._0.Models.VOC_CUSTODIAN>
#{
ViewBag.Title = "List of Custodians";
}
<h2>Index</h2>
<p>
#if (User.IsInRole("Manager"))
{
#Html.ActionLink("Create New", "Create")
}
</p>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list2").jqGrid({
url: '#Url.Action("GridData", "Custodian")',
datatype: 'json',
mtype: 'GET',
colNames: ['Agent ID', 'Branch', 'Unique ID', 'Custodian Name', /*'NRIC No', 'E-Mail', 'Contact No', 'Mobile No',*/'Role', 'Details', 'Edit', 'Delete'],
colModel: [
{ name: 'Agent ID', index: '', width: 10, align: 'left' },
{ name: 'Branch', index: '', width: 10, align: 'left' },
{ name: 'Unique ID', index: '', width: 10, align: 'left' },
{ name: 'Custodian Name', index: '', width: 10, align: 'left' },
{name: 'Role', index: '', width: 10, align: 'left' },
{ name: 'Details', index: '', width: 5, align: 'left' }
, { name: 'Edit', index: '', width: 5, align: 'left' }
,{ name: 'Delete', index: '', width: 5, align: 'left' }
],
pager: jQuery('#pager2'),
rowNum: 10,
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
autowidth: true,
caption: 'Custodians List'
});
});
</script>
#using (Html.BeginForm())
{
<table id="list2" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager2" class="scroll" style="text-align:center;"></div>
}
Controller
public ActionResult GridData (string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = db.VOC_CUSTODIAN.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from custo in db.VOC_CUSTODIAN.AsEnumerable()
select new
{
id = custo.Idx,
cell = new string []
{
custo.StaffId,
custo.Branch,
custo.UniqueId,
custo.Name,
custo.Role,
("<a href='"+ #Url.Action("Details", "Custodian") +"/"+ custo.Idx+ "'>DETAILS</a>"),
("<a href='"+ #Url.Action("Edit", "Custodian") +"/"+ custo.Idx+ "'>EDIT</a>"),
("<a href='"+ #Url.Action("Delete", "Custodian") +"/"+ custo.Idx+ "'>DELETE</a>")
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Your view should not handle the logic, your Controller Action should. You should be able to do something like this with Roles.InUserInRole:
if (!Roles.IsUserInRole(User.Identity.Name, "Managers"))
{
jsonData.total = 1;
jsonData.page = 1;
jsonData.records = 1;
jsonData.rows = jsonData.rows.Where(x => x.id = currentUserId).ToArray()
}
return Json(jsonData, JsonRequestBehavior.AllowGet);
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]);
}
}