jqGrid: layout is broken? - asp.net-mvc-3

i am using a jqgrid in a Dialog but it looks like the layout is broken:
Search button at bottom grid appears twice?
The font is too large.
When i display the grid as a normal view there are no issues.
index.cshtml to open the popup:
<div id="btnGo">
<img id="UserProfileLookUp" src="../../Content/images/ui-flag_blue.png" />
</div>
<script>
$(document).ready(function () {
$('#btnGo').click(function () {
$("#Dialog").dialog("open");
});
$("#Dialog").dialog({
modal: true,
autoOpen: false,
height: 413,
width: 626
});
});
</script>
<div id="Dialog" title="Product Select" style="display: none;">
#{Html.RenderAction("Test", "Home");}
</div>
the actual jqgrid:
<link href="#Url.Content("~/Content/site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jqGrid/jquery-ui-jqgrid.css")" rel="stylesheet" type="text/css" />
#{ ViewBag.Title = "jqGrid in ASP.NET MVC - Searching [Advanced]"; }
<table id="jqgProducts" cellpadding="0" cellspacing="0">
</table>
<div id="jqgpProducts" style="text-align: center;">
</div>
<div id="dlgSupplier">
</div>
<script id="tmplSupplier" type="text/x-jquery-tmpl">
${CompanyName}<br /><br />
${Address}<br />
${PostalCode}, ${City}<br />
${Country}<br /><br />
${Phone}<br />
${HomePage}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#jqgProducts').jqGrid({
//url from wich data should be requested
url: '#Url.Action("Products")',
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: ['ProductID', 'ProductName', 'Supplier', 'Category', 'QuantityPerUnit', 'UnitPrice', 'UnitsInStock'],
//columns model
colModel: [
{ name: 'ProductID', index: 'ProductID', align: 'left', search: true, stype: 'text', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'ProductName', index: 'ProductName', align: 'left', search: true, stype: 'text', searchoptions: { sopt: ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn','nc']} },
{ name: 'Supplier', index: 'SupplierID', align: 'left', search: true, stype: 'select', searchoptions: { sopt: ['eq', 'ne'], dataUrl: '#Url.Action("Suppliers")' } },
{ name: 'Category', index: 'CategoryID', align: 'left', search: true, stype: 'select', searchoptions: { sopt: ['eq', 'ne'], dataUrl: '#Url.Action("Categories")' } },
{ name: 'QuantityPerUnit', index: 'QuantityPerUnit', align: 'left', search: false },
{ name: 'UnitPrice', index: 'UnitPrice', align: 'left', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, prefix: '$' }, search: false },
{ name: 'UnitsInStock', index: 'UnitsInStock', align: 'left', search: false }
],
//pager for grid
pager: $('#jqgpProducts'),
//number of rows per page
rowNum: 5,
//initial sorting column
sortname: 'ProductID',
//initial sorting direction
sortorder: 'asc',
//we want to display total records count
viewrecords: true,
//grid height
height: '100%'
});
$('#jqgProducts').jqGrid('navGrid', '#jqgpProducts', { edit: false, add: false, del: false, search: false }).jqGrid('navButtonAdd', '#jqgpProducts', {
caption: 'Search',
buttonicon: 'ui-icon-search',
onClickButton: function() {
$('#jqgProducts').jqGrid('searchGrid', { multipleSearch: true });
},
position: 'last',
title: 'Search'
});
$('#dlgSupplier').dialog({ autoOpen: false, bgiframe: true, resizable: false, title: 'Supplier' });
$('a[data-supplier-id]').live('click', function (e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
var dialogPosition = $(this).offset();
$.post('#Url.Action("Edit")', { id: $(this).attr('data-supplier-id') }, function(data) {
});
});
});
</script>
controller:
public ActionResult Index()
{
return View();
}
public ActionResult Test()
{
return PartialView();
}

Related

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>

Formatters give incorrect result after sort or search

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/

why react's babel throws duplicate object error, jqgrid on IE?

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.

asp.net-MVC Edit GridDate based on the role

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

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

Resources