hi i want create dynamic multiple jqgrid .but create one jqgrid
fisrt dynamic this down html
<div dir='rtl' align='center' class='table - responsive'><div class='row well'>
<table id='dataArray' cellpadding='0' cellspacing='0'></table>
<div id="pager_dataArray"></div>
</div>
</div>
<br />
<div dir='rtl' align='center' class='table - responsive'>
<div class='row well'>
<table id='dataArray2' cellpadding='0' cellspacing='0'></table>
<div id="pager_dataArray2"></div>
</div>
</div>
then use js code for create jqgrid ;plase pay attention iam for get model and header grid call function in js file,
LoadGrid()
data: LoadGrid(),
colNames: getColNames(LoadGrid()[0]),
colModel: getColModels(LoadGrid()[0]),
var searchOptions = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'bw', 'bn', 'in', 'ni', 'ew', 'en', 'cn', 'nc'];
$(document).ready(function () {
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var today = d.getFullYear() + '/' +
(('' + month).length < 2 ? '0' : '') + month + '/' +
(('' + day).length < 2 ? '0' : '') + day;
$("#dynamicGrouping").change(function () {
var groupingName = $(this).val();
alert(groupingName)
if (groupingName) {
//$('#list').jqGrid('groupingGroupBy', ['AddDate_D', 'Name_c']);
$('#' + gridid).jqGrid('groupingGroupBy', [groupingName]);
} else {
$('#' + gridid).jqGrid('groupingRemove');
}
});
caption: "تست گرید",
$('#' + gridid).jqGrid({
caption: "تست گرید",
//url from wich data should be requested
// url: '#Url.Action("GetProducts","Home")',
datatype: 'local',
//این تابع از فایل androidfunction فراخوانی می شود
data: LoadGrid(),
colNames: getColNames(LoadGrid()[0]),
colModel: getColModels(LoadGrid()[0]),
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: true,
userdata: "UserData",
id: "Id",
cell: "RowCells"
},
grouping: true,
iconSet: "glyphIcon",
groupingView: {
// groupField: ['AddDate_D' , 'Name_c'],
groupColumnShow: [true],
groupText: ['<b>{0}</b>'],
groupCollapse: true,
groupOrder: ['asc'],
groupSummary: [true]
},
cmTemplate: { editable: false, autoResizable: true },
toppager: true,
// groupingView: { groupField: ['AddDate_D'] },
mtype: 'POST',
footerrow: true,
// userDataOnFooter : true,
//gridComplete: function () {
// var $grid = $("#FooTable");
// var colSum = $grid.jqGrid('getCol', 'Price_Num', false, 'sum');
// $grid.jqGrid('footerData', 'set', { price: colSum });
//},
pager: $('#' + pagegrid),
//number of rows per page
rowNum: 10,
rowList: [10, 20, 50, 100],
//initial sorting column
sortname: 'Id',
//initial sorting direction
sortorder: 'asc',
// loadonce: true,
shrinkToFit: true,
//we want to display total records count
viewrecords: true,
width: 'auto',
height: 'auto',
hidegrid: false,
direction: "rtl",
gridview: true,
altRows: true,
rownumbers: true,
autoencode: true,
treeGrid: true,
treeGridModel: 'adjacency',
ExpandColClick: true,
// ignoreCase: true,
//loadComplete : function() {
// var table = this;
// setTimeout(function(){
// updatePagerIcons(table);
// }, 0);
//},
loadComplete: function () {
sumarValores($(this))
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
},
})
.navGrid(
$('#' + pagegrid),
//enabling buttons
{ add: false, del: false, edit: false, search: false },
//edit option
{
width: 'auto', checkOnUpdate: true, checkOnSubmit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#' + gridid));
}
},
//add options
{
width: 'auto', url: '#Url.Action("AddProduct","Home")',
},
//add options
//delete options
{
url: '#Url.Action("DeleteProduct","Home")', reloadAfterSubmit: false
})
.jqGrid('inlineNav', $('#' + pagegrid),
{
// cloneToTop: true,
edit: false, add: true, save: false, cancel: false,
edittext: "ویرایش", addtext: "جدید", savetext: "ذخیره", canceltext: "لغو",
addParams: {
// اگر میخواهید ردیفهای جدید در ابتدا ظاهر شوند، این سطر را حذف کنید
position: "first", //ردیفهای جدید در آخر ظاهر میشوند
rowID: '_empty',
useDefValues: true,
addRowParams: getInlineNavParams(true)
},
editParams: getInlineNavParams(false)
}
)
$('#' + gridid).jqGrid('navButtonAdd', '#list_toppager',
{
caption: ""/*"Show"*/, buttonicon: "ui-icon-extlink", title: "Show Link",
onClickButton: function () {
var grid = $('#' + gridid);
var rowid = grid.jqGrid('getGridParam', 'selrow');
window.location = grid.jqGrid('getCell', rowid, 'dataUrl');
}
});
$('#' + gridid).jqGrid('filterToolbar', {
stringResult: true,//// وجود این سطر سبب میشود تا اپراتورها به سرور ارسال شوند
enableClear: false,
searchOnEnter: true,
searchOperators: true, // فعال سازی منوی اپراتورها
defaultSearch: "cn"
});
function getSelectedRow() {
var grid = $('#' + gridid);
var rowKey = grid.jqGrid('getGridParam', "selrow");
if (rowKey)
alert("Selected row primary key is: " + rowKey);
else
alert("No rows are selected");
}
});
function sumarValores($self) {
var sumaHa = 0;
var columnNames = $('#' + gridid).jqGrid('getGridParam', 'colNames');
var global;
var footer = {};
for (var z = 0; z < columnNames.length; z++) {
var colN = columnNames[z];
// $self.jqGrid("footerData", "set", footer);
if (colN == "Price") {
colN = colN.concat('_Num');
var sumtotal = $self.jqGrid("getCol", colN, false, "sum");
// global = colN;
global = 'Price_Num';
footer[global] = sumtotal;
//$self.jqGrid("footerData", "set", {
// Price_Num: sumtotal,
//});
$self.jqGrid("footerData", "set", footer);
break;
}
if (colN == "AddDate") {
global = 'AddDate_D';
var sumtotald = $self.jqGrid("getCol", colN, false, "sum");
// footer[global] = sumtotald;
$self.jqGrid("footerData", "set",
{
AddDate_D: sumtotald,
}
);
}
}
}
function getInlineNavParams(isAdd) {
return {
// استفاده از آدرسهای مختلف برای حالات ویرایش و ثبت اطلاعات جدید
url: isAdd ? '#Url.Action("AddUser", "Home")' : '#Url.Action("EditUser","Home")',
key: true,
restoreAfterError: false, // این مورد سبب میشود تا اعتبارسنجی سمت سرور قابل اعمال شود
oneditfunc: function (rowId) {
// نمایش دکمههای ذخیره و لغو داخل همان سطر
$("#jSaveButton_" + rowId).show();
$("#jCancelButton_" + rowId).show();
},
successfunc: function () {
var $self = $(this);
setTimeout(function () {
$self.trigger("reloadGrid"); // دریافت کلید اصلی ردیف از سرور
}, 50);
},
errorfunc: function (rowid, response, stat) {
if (stat != 'error') // this.Response.StatusCode == 200
return;
var result = $.parseJSON(response.responseText);
if (result.success === false) {
//نمایش خطای اعتبار سنجی سمت سرور پس از ویرایش یا افزودن
$.jgrid.info_dialog($.jgrid.errors.errcap,
'<div class="ui-state-error">' + result.message + '</div>',
$.jgrid.edit.bClose,
{ buttonalign: 'center' });
}
}
};
}
function centerDialog(form, grid) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
}
function getColNames(data, status) {
var keys = [];
if (status != 'headr') {
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push((key.split('_'))[0]);
}
}
keys.push('');
}
else {
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.push('');
}
return keys;
}
function getColModels(data) {
var colNames = getColNames(data, 'headr');
var colModelsArray = [];
for (var i = 0; i < colNames.length; i++) {
var str;
if (i === 0) {
str = {
name: (colNames[i]),
index: (colNames[i]),
key: true,
editable: false,
search: false,
width: 20,
};
} else if (i >= 1 && i <= colNames.length - 2) {
switch ((colNames[i].split('_'))[1]) {
case ('Num'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
summaryType: 'sum', summaryTpl: '<b>جمع مشاهدات: {0}</b>',
//width: 100,
searchoptions: { sopt: searchOptions },
formatter: 'currency',
formatoptions:
{
decimalSeparator: '.',
thousandsSeparator: ',',
decimalPlaces: 0,
prefix: 'ريال'
},
editable: true, edittype: 'text',
// summaryType: function (val, name, record) {
};
// tt = 'Price_Num';
break;
case ('D'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
// width: 100,
searchoptions: {
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'm/d/y',
onClose: function (event) {
$('#' + gridid).trigger("reloadGrid", [{ page: 1 }]);
}
});
// datepicker({
// dateFormat: 'dd/mm/yy',
// changeYear: true,
// changeMonth: true,
// showWeek: true,
// onSelect: function (dateText, inst) {
// setTimeout(function () {
// $('#' + gridid)[0].triggerToolbar();
// }, 100);
// }
//});
},
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'm/d/y',
onClose: function (event) {
$('#' + gridid).trigger("reloadGrid", [{ page: 2 }]);
}
});
}
, sopt: searchOptions
},
editoptions: {
maxlength: 10,
onclick: 'PersianDatePicker.Show(this,' + '1395/02/01' + ')'
},
editrules: {
required: true
}
};
break;
case ('c'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
//width:100,
searchoptions: { sopt: searchOptions },
};
break;
default:
// alert('>41');
}
}
else {
str = {
name: 'myac',
index: colNames[i],
resize: false,
fixed: true, sortable: false,
formatter: 'actions',
search: false,
formatoptions: {
keys: true
},
}
}
//formatter: 'currency',
//formatoptions:
//{
// decimalSeparator: '.',
// thousandsSeparator: ',',
// decimalPlaces: 2,
// prefix: '$'
//},
//editable: true, edittype: 'text',
colModelsArray.push(str);
}
return colModelsArray;
}
function updatePagerIcons(table) {
//var replacement =
//{
// 'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
// 'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
// 'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
// 'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
//};
//$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
// var icon = $(this);
// var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
// if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
//})
}
$(document).ready(function () {
function LoadGrid() {
object = {
"dataArray":
[
{ id_R: 1, Name_c: "dummy1", AddDate_D: "1394/07/27", Price_Num: "10000" },
{ id_R: 2, Name_c: "dummy2", AddDate_D: "1394/07/28", Price_Num: "120000" },
],
"dataArray2":
[
{ id_R: 9, Name2_c: "dummy9", AddDate2_D: "1393/04/28", Price2_Num: "200000" },
{ id_R: 10, Name_c: "dummy10", AddDate_D: "1393/04/04", Price_Num: "2100000" },
]
};
// برای مپ کردن ارایه یه ارایه دیگر
//departement = $.map(dataArray, function (value, index) {
// return [value];
//});
var names = Object.getOwnPropertyNames(object);
// var names = 'grd1'
var col = [];
var gridarr = [];
var pagegrarr = [];
//مقادیر ارایه را در متغیر زیر می ریزد
var col = Object.values(object);
//تعداد ارایه برای گرید بدست اوردیم
var countarr = col.length;
for (var i = 0; i < countarr; i++) {
//اسم جدول گرید
gridarr[i] = names[i];
pagegrarr[i] = 'pager_' + names[i];
// return col[i];
}
flag++;
switch (flag) {
case 1:
case 2:
case 3:
case 4:
gridid = gridarr[0]
pagegrid = pagegrarr[0]
return col[0];
break;
case 5:
case 6:
case 7:
case 8:
gridid = gridarr[1]
pagegrid = pagegrarr[1]
return col[1];
break;
default:
break;
}
}
});
this answer:
<script>
$(document).ready(function () {
function grid(tt) {
//=== LOCA VARIABLES ===//$.jgrid.randId()
var myGrid = $("<table>").attr("id", tt);
var myPager = $("<div>").attr("id", tt +"_pager");
var localData1 = {
"page": 1,
"totalRecords": 5,
"pageSize": 3,
"rows": [
{ Name: "Name 1" },
{ Name: "Name 3" },
{ Name: "Name 2" }
]
};
function publicInit() {
$("body").append(myGrid, myPager);
myGrid.jqGrid({
pager: myPager,
data: localData1.rows,
datatype: "local",
colModel: [
{ name: 'Name', index: 'Name', width: "500" }
],
//localReader: {
// repeatitems: false
// },
// rowNum: 3,
viewrecords: true,
height: "auto",
ignoreCase: true
});
}
//=== REVEALING PATTERN===//
return {
init: publicInit
}
};
var grid1 = new grid("y");
grid1.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid("c");
grid2.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid("b");
grid2.init();
});
</script>
Related
I have a page (Steps_Details.cshtml) with a jqgrid in MVC that i want to call it in 3 ways and it loads data based on the Unique_code i send as parameter. 1st way) i have another page (Rep_Contracts_Steps.cshtml) with a jqgrid and i have a link button in it and by clicking on this link button and sending the parameter data loads properly. 2nd way) a link on main menu with no parameters and it loads all data with no filtering.
the 3rd way and the one I've encountered problem with ) i have a button in a page and i send the parameter. it directs to the view but doesn't load the page.(in fact it doesn't call the "Get_Contracts_Steps_Details" Action in my HomeController when i use btnRep)
"Steps_Details.cshtml"
<script type="text/javascript">
$(document).ready(function () {
$('#list').jqGrid({
caption: "گزارش جزییات پیگیری قراردادها",
url: '#Url.Action("Get_Contracts_Steps_Details","Home")',
datatype: 'json',
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: true,
userdata: "UserData",
id: "Vahed_Descript",
cell: "RowCells"
},
mtype: 'GET',
//columns names
colNames: [' ردیف ',
' کد تایید ',
' عنوان تایید ',
' کاربر تایید کننده ',
' تاریخ تایید ',
' توضیحات',
' کاربر ثبت کننده',
' تاریخ ثبت',
' کاربر ویرایش کننده' ,
' تاریخ ویرایش' ,
' عنوان واحد ',
' کد دبیرخانه ',
' شماره درخواست ',
' شرح درخواست ',
' تاریخ ثبت درخواست',
' مبلغ برآوردی ',
''
],
//columns model
colModel: [
{ name: 'MCS_ID', index: 'MCS_ID', align: 'Right', width: "60px", editable: true, editoptions: { readonly: "readonly" } },
{ name: 'MCS_ConfirmId', index: 'MCS_ConfirmId', align: 'Right', width: "60px", editable: false },
{ name: 'MWL_Descript', index: 'MWL_Descript', align: 'Right', editable: false },
{ name: 'MCS_ConfirmUser', index: 'MCS_ConfirmUser', align: 'Right', editable: true, edittype: 'text' },
{ name: 'MCS_ConfirmDate', index: 'MCS_ConfirmDate', align: 'Right', width: "80px", editable: true, edittype: 'text',
editrules: { required: true }
},
{ name: 'MCS_Note', index: 'MCS_Note', align: 'Right', width: "300px", editable: true, edittype: 'text' },
{ name: 'MCS_CreatorUserName', index: 'MCS_CreatorUser', align: 'Right', editable: false },
{ name: 'MCS_Creation_Date', index: 'MCS_Creation_Date', align: 'Right', width: "80px", editable: false },
{ name: 'MCS_EditorUserName', index: 'MCS_EditorUserName', align: 'Right', editable: false },
{ name: 'MCS_EditDate', index: 'MCS_EditDate', align: 'Right', width: "80px", editable: false },
{ name: 'DESCRIPT', index: 'DESCRIPT', align: 'right', editable: false },
{ name: 'DABIR_VAHED_CODE', index: 'DABIR_VAHED_CODE', align: 'right', width: "60px", editable: false },
{ name: 'CONTRACT_REQ_ID', index: 'CONTRACT_REQ_ID', align: 'right', width: "100px", editable: false },
{ name: 'CONTRACT_REQ_SUBJECT', index: 'CONTRACT_REQ_SUBJECT', align: 'right', editable: false },
{ name: 'D_CONTRACT_REQ', index: 'D_CONTRACT_REQ', align: 'right', width: "100px", editable: false },
{ name: 'AMNT_TOT_ESTIMATE', index: 'AMNT_TOT_ESTIMATE', align: 'right', width: "100px", editable: false,
formatter: 'currency', formatoptions:
{ decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 0 }
},
{ name: 'MCS_REQ_UNIQUE', index: 'MCS_REQ_UNIQUE', width: 1, align: 'left', hidden: true },
],
pager: $('#pager'),
rowNum: 200,
rowList: [10, 20, 40, 60, 80, 100, 150, 200, 300],
sortname: 'CONTRACT_REQ_SUBJECT',
sortorder: 'asc',
viewrecords: true,
altRows: true,
shrinkToFit: false,
width: 'auto',
height: '300px',
hidegrid: false,
direction: "rtl",
gridview: true,
rownumbers: true,
footerrow: true,
userDataOnFooter: true,
scrollerbar: true,
loadComplete: function () {
$("tr.jqgrow:odd").css("background", "#E0E0E0");
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
}
, loadonce: true
})
.jqGrid('navGrid', "#pager",
//enabling buttons
{ add: false, del: true, edit: true, search: true, refresh: true },
//edit option
{
url: '#Url.Action("EditSteps_Details", "Home")' ,
width: 'auto',
checkOnUpdate: true,
checkOnSubmit: true,
closeOnEscape: true,
closeAfterEdit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#list'));
},
afterSubmit: function (response, postdata) {
$("#list").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
return [true, "", ''];
},
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
//delete options
{
url: '#Url.Action("DeleteSteps_Details", "Home")', reloadAfterSubmit: false
, beforeShowForm: function (form) {
centerDialog(form, $('#list'));
},
});
function centerDialog(form, grid) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
}
function toolbarSearching() {
$("#list").jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
};
$("#list").jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
var maxNameLength = 10;
$("input[id=gs_name]").blur(function () {
var $th = $(this).closest(".ui-search-toolbar>th"),
colIndex = $th[0].cellIndex,
$colHeader = $th.parent().siblings(".ui-jqgrid-labels").children("th").eq(colIndex),
colHeaderText = $colHeader.children("div").text();
if (this.value.length > maxNameLength) {
alert(colHeaderText + ' is longer than ' + maxNameLength + ' characters.');
}
});
$('#gs_invdate').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true
});
})
</script>
"Steps_Details" Action
[HttpGet]
public ActionResult Steps_Details(string REQ_UNIQE)
{
if (Session["LoginName"] == null)
{
return RedirectToAction("Index", "Home");
}
else
{
if (REQ_UNIQE != null)
{
if (REQ_UNIQE != "")
{
Session["REQ_UNIQE"] = REQ_UNIQE.ToString();
}
}
return View();
}
}
"button and the dropdownlist that i send the value of it as a parameter"
<div class="form-group">
#Html.DropDownListFor(model => model.Req_Unique, (SelectList)ViewBag.Contract_Req_Sub_List, "انتخاب", new { #class = "form-control", #id = "ddlContrReqSub", #onchange = "javascript:GetWork_Level(this.value);" })
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" />
</div>
"javascript code for btnRep"
$(document).ready(function () {
$("#btnRep").click(function () {
var REQ_UNIQE = $("#ddlContrReqSub").val();
$.ajax({
url: "/Home/Steps_Details",
type: "GET",
data: { REQ_UNIQE: REQ_UNIQE },
});
});
});
"Get_Contracts_Steps_Details Action in HomeController"
[HttpGet]
public ActionResult Get_Contracts_Steps_Details(JqGridRequest request )
{
using (rw_mis_dbEntities dc = new rw_mis_dbEntities())
{
if (Session["REQ_UNIQE"] != null )
{
var list = dc.MVC_REP_Contracts_Steps_Details_By_Req_Unique(Security.SharedMembers.shrd_Year_Abbr, Security.SharedMembers.shrd_Vahed_Id, Security.SharedMembers.shrd_User_Id, "", "", 0, new Guid(Session["REQ_UNIQE"].ToString())).ToList();
var pageIndex = request.page - 1;
var pageSize = request.rows;
var totalRecords = list.Count;
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var contractsQuery = list.AsQueryable();
contractsQuery = new JqGridSearch().ApplyFilter(contractsQuery, request._search, request.searchField, request.searchString,
request.searchOper, request.filters, this.Request.Form);
if (string.IsNullOrWhiteSpace(request.oper))
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize)
.Take(pageSize);
}
else if (request.oper == "excel")
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize);
}
var contractsList = contractsQuery
.OrderBy(request.sidx + " " + request.sord)
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
var jqGridData = new JqGridData
{
UserData = new // نمايش در فوتر
{
Name = "جمع صفحه"
},
Total = totalPages,
Page = request.page,
Records = totalRecords,
Rows = (contractsList.Select(Contract => new JqGridRowData
{
Id = Convert.ToInt32(Contract.MCS_ID),
RowCells = new List<string>
{ Contract.MCS_ID.ToString(),
Contract.MCS_ConfirmId.ToString(),
Contract.MWL_Descript,
Contract.MCS_ConfirmUser,
Contract.MCS_ConfirmDate.ToString() ,
Contract.MCS_Note ,
Contract.MCS_CreatorUserName.ToString() ,
Contract.MCS_CreationDate.ToString() ,
Contract.MCS_EditorUserName.ToString() ,
Contract.MCS_EditDate .ToString() ,
Contract.VAHED_DESCRIPT ,
Contract.DABIR_VAHED_CODE,
Contract.CONTRACT_REQ_ID ,
Contract.CONTRACT_REQ_SUBJECT ,
Contract.D_CONTRACT_REQ ,
Contract.AMNT_TOT_ESTIMATE.ToString() ,
Contract.MCS_REQ_UNIQUE.ToString ()
}
})).ToList()
};
Session["REQ_UNIQE"] = null;
return Json(jqGridData, JsonRequestBehavior.AllowGet);
}
else
{
var list = dc.MVC_REP_Contracts_Steps_Details(Security.SharedMembers.shrd_Year_Abbr, Security.SharedMembers.shrd_Vahed_Id, Security.SharedMembers.shrd_User_Id, "", "", 0 ).ToList();
var pageIndex = request.page - 1;
var pageSize = request.rows;
var totalRecords = list.Count;
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var contractsQuery = list.AsQueryable();
contractsQuery = new JqGridSearch().ApplyFilter(contractsQuery, request._search, request.searchField, request.searchString,
request.searchOper, request.filters, this.Request.Form);
if (string.IsNullOrWhiteSpace(request.oper))
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize)
.Take(pageSize);
}
else if (request.oper == "excel")
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize);
}
var contractsList = contractsQuery
.OrderBy(request.sidx + " " + request.sord)
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
var jqGridData = new JqGridData
{
UserData = new // نمايش در فوتر
{
Name = "جمع صفحه"
},
Total = totalPages,
Page = request.page,
Records = totalRecords,
Rows = (contractsList.Select(Contract => new JqGridRowData
{
Id = Convert.ToInt32(Contract.MCS_ID),
RowCells = new List<string>
{ Contract.MCS_ID.ToString(),
Contract.MCS_ConfirmId.ToString(),
Contract.MWL_Descript,
Contract.MCS_ConfirmUser,
Contract.MCS_ConfirmDate.ToString() ,
Contract.MCS_Note ,
Contract.MCS_CreatorUserName.ToString() ,
Contract.MCS_CreationDate.ToString() ,
Contract.MCS_EditorUserName.ToString() ,
Contract.MCS_EditDate .ToString() ,
Contract.VAHED_DESCRIPT ,
Contract.DABIR_VAHED_CODE,
Contract.CONTRACT_REQ_ID ,
Contract.CONTRACT_REQ_SUBJECT ,
Contract.D_CONTRACT_REQ ,
Contract.AMNT_TOT_ESTIMATE.ToString() ,
Contract.MCS_REQ_UNIQUE.ToString ()
}
})).ToList()
};
return Json(jqGridData, JsonRequestBehavior.AllowGet);
}
}
}
Thanks in advance
I just changed
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" />
To
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" onclick="location.href='#Url.Action("Steps_Details", "Home")?Req_Unique=' + $('#ddlcontrreqsub').val()" />
and it worked
Method Get_Contracts_Steps_Details is with return type ActionResult. But jqGrid defined with datatype:'json'.
If Get_Contracts_Steps_Details is going to return json result for jqGrid, use return type string or JsonResult.
I have a datatable. I want to retrieve the ID values of the rows that are selected.
How can I do that.
My codes:
var DatatableRecordSelectionDemo = function () {
var demo = function () {
var url = '/Data/default.json';
$.getJSON(url, function (data) {
var datatable = $('.m_datatable').mDatatable({
data: {
type: "local",
source: data,
pageSize: 10,
saveState: {
cookie: true,
webstorage: true
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
// layout definition
layout: {
theme: 'default', // datatable theme
"class": '', // custom wrapper class
scroll: false, // enable/disable datatable scroll both horizontal and vertical when needed.
height: 550, // datatable's body's fixed height
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
// columns definition
columns: [{
field: "RecordID",
title: "#",
sortable: false, // disable sort for this column
width: 40,
textAlign: 'center',
selector: { class: 'm-checkbox--solid m-checkbox--brand' }
}, {
field: "OrderID",
title: "Numara",
// sortable: 'asc', // default sort
filterable: true, // disable or enable filtering
// basic templating support for column rendering,
template: '{{OrderID}} - {{ShipCountry}}'
}, {
field: "ShipName",
title: "Adı"
}, {
field: "Status",
title: "Durumu",
// callback function support for column rendering
template: function (row) {
var status = {
true: { 'title': 'Aktif', 'class': ' m-badge--success' },
false: { 'title': 'Pasif', 'class': ' m-badge--danger' }
};
return '<span class="m-badge ' + status[row.Status].class + ' m-badge--wide">' + status[row.Status].title + '</span>';
}
}, {
field: "Actions",
title: "İşlem",
width: 100,
sortable: false,
overflow: 'visible',
template: function (row) {
var tblName = String(row.ShipName).replace(/'/g, "\\'");
var tblid = String(row.RecordID);
return '\
<a href="#" onclick="Modalac('+ tblid + ',\'' + tblName + '\',' + row.Status + ')" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Düzenle">\
<i class="la la-edit"></i>\
</a>\
<a href="#" onclick="Sil('+ tblid + ',\'' + tblName + '\')" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill" title="Sil">\
<i class="la la-trash"></i>\
</a>\
';
}
}]
});
var query = datatable.getDataSourceQuery();
$('#m_form_search').on('keyup', function (e) {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.generalSearch = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(query.generalSearch);
$('#m_form_status').on('change', function () {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Status = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Status !== 'undefined' ? query.Status : '');
$('#m_form_status').selectpicker();
// on checkbox checked event
$('.m_datatable').on('m-datatable--on-check', function (e, args) {
var count = datatable.setSelectedRecords().getSelectedRecords().length;
$('#m_datatable_selected_number').html(count);
if (count > 0) {
$('#m_datatable_group_action_form').collapse('show');
}
})
.on('m-datatable--on-uncheck m-datatable--on-layout-updated', function (e, args) {
var count = datatable.setSelectedRecords().getSelectedRecords().length;
$('#m_datatable_selected_number').html(count);
if (count === 0) {
$('#m_datatable_group_action_form').collapse('hide');
}
});
$('.m_datatable tbody').on('click', 'tr', function (){
var id = this.RecordID;
var index = $.inArray(id, selected);
if (index === -1)
{
selected.push(id);
} else
{
selected.splice(index, 1);
}
$(this).toggleClass('selected');
});
});
};
return {
// public functions
init: function () {
demo();
}
};
}();
var TopluIslem = function () {
var datatable = $('.m_datatable').mDatatable();
var dataArr = [];
$.each($(".m_datatable tr.selected"),function(){
dataArr.push($(this).find('td').eq(0).text());
});
console.log(dataArr);
alert(rowCount);
};
jQuery(document).ready(function () {
DatatableRecordSelectionDemo.init();
});
İşlem Yap
I solved the problem
var secilenler = [];
$('.m_datatable').on('m-datatable--on-check', function(e, args) {
secilenler.push(args.toString());
}).on('m-datatable--on-uncheck', function (e, args) {
var i = secilenler.indexOf(args.toString());
if(i !== -1) {
secilenler.splice(i, 1);
}
});
I need to trap when the user presses ENTER in edit mode and this code works every time any other key gets pressed but not ENTER.
Any ideas why? maybe there is an automatic setting that needs to be set to false?
$(dispgrid).jqGrid({
url: als.common.getServerPath() + 'WorkorderAjax/GetDispositionFields',
datatype: 'local',
mtype: 'POST',
height: 292,
width: 480,
caption: 'Disposition Instructions',
hidegrid: false,
loadtext: 'Please wait,</br>loading disposition fields...',
colModel: [
{ name: 'Description', label: 'Description', sortable: false, width: 120, align: 'left' },
{ name: 'Fraction', label: 'Split', sortable: false, width: 40, align: 'center' },
{
name: 'Disposition', label: 'Disposition', sortable: false, align: 'left',
editable: true, edittype: 'select', classes: 'disposition_list'
},
{ name: 'PickList', label: 'PickList', sortable: false, hidden: true },
{
name: 'FreeDays', label: 'FreeDays', sortable: false, editable: true
},
{ name: 'MaxFreeDays', label: 'MaxFreeDays',hidden: true }
],
pgbuttons: false,
pginput: false,
rowNum: 999,
loadComplete: function () {
currentRowId = undefined;
prevRowId = undefined;
prevRowModified = false;
},
onSelectRow: function (rowId) {
if (prevRowId !== undefined) {
if (prevRowModified) {
//validate free days here
var selRowId = $(dispgrid).jqGrid('getGridParam', 'selrow');
var freedays = $("#" + prevRowId + "_FreeDays", dispgrid).val();
var maxfreedays = $(dispgrid).jqGrid('getCell', selRowId, 'MaxFreeDays');
if (parseInt(freedays) > parseInt(maxfreedays)) {
$(dispgrid).jqGrid('restoreRow', selRowId);
showErrorDialog("Free days can not be larger than " + maxfreedays);
$(dispgrid).resetSelection();
$(dispgrid).setSelection(prevRowId, false);
return true;
}
saveparameters = {
url: als.common.getServerPath() + 'WorkorderAjax/UpdateDispositionFields',
extraparam: {
folderno: wo,
fraction: prevRowId,
disposition: $('#' + prevRowId + '_Disposition', this).val(),
freedays: $('#' + prevRowId + '_FreeDays', this).val()
},
successfunc: function () {
$(this).trigger("reloadGrid");
prevRowModified = false;
$(this).restoreRow(prevRowId);
return true;
}
};
$(this).jqGrid('saveRow', prevRowId, saveparameters);
}
else {
$(this).restoreRow(prevRowId);
}
}
currentRowId = rowId;
var rowData = $(this).jqGrid('getRowData', currentRowId);
var unformatted = rowData.PickList;
var formatted = '';
var ar = unformatted.split(',');
for (var i = 0; i < ar.length; i++) {
formatted += ar[i] + ':' + ar[i]
+ (i < ar.length - 1 ? ';' : '');
}
$(this).setColProp('Disposition', { editoptions: { value: formatted } });
saveparameters = {
url: als.common.getServerPath() + 'WorkorderAjax/UpdateDispositionFields',
extraparam: {
folderno: wo,
fraction: currentRowId,
disposition: $('#' + currentRowId + '_Disposition', this).val()
},
successfunc: function () {
$(this).trigger("reloadGrid");
prevRowModified = false;
return true;
},
keys: true
};
$(this).editRow(currentRowId, saveparameters);
prevRowId = currentRowId;
}
}).closest('div.ui-jqgrid-view').children('div.ui-jqgrid-titlebar').css('text-align', 'center').
children('span.ui-jqgrid-title').css('float', 'none');
$(dispgrid).on('change', '', function () { prevRowModified = true; });
$(dispgrid).on('keydown', '', function (e) {
//the break point here gets hit every time unless the user presses ENTER key
if (e.keyCode == 13) {
}
});
keys:false in the saveparameters did the trick
I'm using jqgrid inline edit in which i have a scenario to invoke the "cancel edit" button event and throw a message "Are you sure to cancel?".
//Code:
//Unload the grid.
$('#CommentsData').jqGrid('GridUnload');
//Comments grid start.
$("#CommentsData").jqGrid({
datastr: tableSrc,
hoverrows: false,
datatype: "jsonstring",
jsonReader: {
id: 'CommentId',
repeatitems: false
},
height: 'auto',
width: 'auto',
hidegrid: false,
gridview: true,
sortorder: 'desc',
sortname: 'DateTime',
pager: '#CommentsPager',
rowList: [], // disable page size dropdown
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: false, // disable current view record text like 'View 1-10 of 100'
caption: "Comments",
colNames: ['DateTime', 'UserName', 'Comments'],
colModel: [
{
name: 'DateTime', index: 'DateTime', width: 120, formatter: "date", sorttype: "date",
formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i A" }
},
{ name: 'UserName', index: 'UserName' },
{ name: 'CommentText', index: 'CommentText', editable: true }],
//Events to add and edit comments.
serializeRowData: function (postdata) {
var filterResult;
var jsonResult;
if (tableSrc == "")
jsonResult = $.parseJSON(commentDetails);
else
//Parse values bind to the comments.
jsonResult = $.parseJSON(tableSrc);
var newResult = new Object();
//Check if operation is edit.
if (postdata.oper == "edit") {
//Filter the edited comments from main source.
newResult = Enumerable.From(jsonResult).Where(function (s) { return s.CommentId = postdata.id }).First();
newResult.CommentText = postdata.CommentText;
}
else {
filterResult = Enumerable.From(jsonResult).First();
newResult.CommentText = postdata.CommentText;
newResult.TransactionId = filterResult.TransactionId;
newResult.TaskId = filterResult.TaskId;
}
filterResult = JSON.stringify(newResult);
$.ajax({
url: '#Url.Action("UpdateComments", "Home")',
datatype: 'json',
data: { 'resultData': filterResult, 'action': postdata.oper },
type: 'POST',
success: OnCompleteComments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
//After update Load the grid.
function OnCompleteComments(result) {
selectTaskComment = false;
$('#dialog').dialog("close");
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
rowList = $('.ui-pg-selbox').val();
Loadgrid($("#TransactionsGrid").getGridParam('page'));
}
},
onSelectRow: function (id) {
selectTaskComment = true;
var thisId = $.jgrid.jqID(this.id);
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
var selectValues = jQuery('#CommentsData').jqGrid('getRowData', id);
thisId = $.jgrid.jqID(this.id);
if (selectValues.UserName == '#ViewBag.UserName' || '#ViewBag.IsAdmin' == 'True') {
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
}
else {
$("#" + thisId + "_iledit").addClass('ui-state-disabled');
$("#del_" + thisId).addClass('ui-state-disabled');
}
}
});
jQuery("#CommentsData").jqGrid('navGrid', '#CommentsPager', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {},
{
//Delete event for comments
url: '#Url.Action("UpdateComments", "Home")',
serializeDelData: function (postData) {
return {
resultData: JSON.stringify(postData.id),
action: JSON.stringify(postData.oper),
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
beforeSubmit: function () {
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
return [true, '', ''];
},
afterSubmit: function (response, postdata) {
selectTaskComment = false;
Loadgrid($("#TransactionsGrid").getGridParam('page'));
return [true, '', ''];
}
});
$('#CommentsData').jqGrid('inlineNav', '#CommentsPager', { edit: true, add: true, save: true, del: false, cancel: true });
$("#CommentsData_iledit").addClass('ui-state-disabled');
$("#del_CommentsData").addClass('ui-state-disabled');
In which event i have to write the code and throw the alert message?
Also if possible, need to know if the above code could be optimized. Because the delete event is written in a separate place comparing edit and add. I'm bit confused if this is right method.
The easiest way to invoke the "cancel edit" button would be executing the code
$("#CommentsData_ilcancel").click(); // trigger click event on Cancel button
where CommentsData is the id of the grid.
I'm checking duplicate username in Add/Edit Action of User Management and handle the code which is as under:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult InsertUser(UserViewModel viewModel)
{
var user = new User
{
UserID = viewModel.UserID,
UserName = viewModel.UserName,
//Password = "123456",
Password = viewModel.Password,
FullName = viewModel.FullName,
Email = viewModel.Email,
CreationDate = DateTime.Now,
IsActive = viewModel.IsActive
};
//Also check here if user already exist, usename shud be unique.
bool isAlreadyExist = new UserManagement().CheckUserName(user.UserName);
if(isAlreadyExist)
{
return Json(false);
}
try
{
new UserManagement().Save(user);
}
catch (Exception)
{
return Json(false);
}
return Json(true);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateUser(UserViewModel viewModel)
{
User user = new UserManagement().GetUserBy(viewModel.UserID);
if (!viewModel.UserName.TrimEnd().Equals(user.UserName.TrimEnd()))
{
bool isAlreadyExist = new UserManagement().CheckUserName(viewModel.UserName);
if (isAlreadyExist)
{
return Json(false);
}
}
user.UserName = viewModel.UserName;
user.Password = viewModel.Password;
user.FullName = viewModel.FullName;
user.Email = viewModel.Email;
user.IsActive = viewModel.IsActive;
try
{
new UserManagement().Save(user);
}
catch
{
return Json(false);
}
return Json(true);
}
The script code in .cshtml is as under:
<script type="text/javascript">
var arrayIds = [];
var roleDropDown = "";
$(document).ready(function () {
$(".ui-dropdownchecklist > div > div > .active").live("change", function () {
var parentId = $(this).parent().parent().parent().attr("Id");
parentId = parentId.substring(0, parentId.length - 4);
$("#" + parentId + " > span > span").text("Assigning...").css("color", "#666666");
//Set Variable to identify Assign or Deassign Role to User
var checked = false;
if ($(this).attr("checked") == "checked") {
checked = true;
}
//Set RoleId
var role = $(this).val();
//Set UserId
var user = $(this).attr('id');
//Start Ajax Call
$.ajax({
url: '#Url.Action("ManageUserRoles", "Role")',
type: "GET",
cache: false,
data: { userid: user, roleid: role, chked: checked },
//async: false,
success: function () {
},
complete: function () {
$("#" + parentId + " > span > span").text("Assign Roles").css("color", "#222222");
}
});
//End Ajax Call
});
roleDropDown = "<select id='_RoleID' multiple='true' style='Display: none;'>";
$.ajax({
url: '#Url.Action("GetAllReoles", "Role")',
type: "GET",
cache: true,
async: false,
success: function (countiesJson) {
$.each(countiesJson, function (index, optionData) {
roleDropDown += "<option value='" + optionData.RoleID + "'>" + optionData.RoleName + "</option>";
});
}
});
roleDropDown += "</select>";
var userGrid = $('#jqgUsers');
var pages = [];
var MAX_PAGERS = 2;
$('#jqgUsers').jqGrid({
//url from wich data should be requested
url: '#Url.Action("FetchUsers")',
//type of data
datatype: 'json',
cache: false,
//url access method type
mtype: 'POST',
postData: {
UserName: function () { return $('#UserName1').val(); },
FullName: function () { return $('#FullName1').val(); },
Email: function () { return $('#Email1').val(); },
IsActive: function () { return $('#IsActive1 option:selected').val(); },
FromDate: function () { return $('#FromDate').val(); },
ToDate: function () { return $('#ToDate').val(); }
},
colNames: ['User ID', 'User Name', 'Password', 'Full Name', 'Email', 'Active', 'Roles', ''],
//columns model
colModel: [
{ name: 'UserID', index: 'UserID', hidden: true, align: 'left', editable: false },
{ name: 'UserName', index: 'UserName', width: 252, align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 50 }, editrules: { required: true} },
{ name: 'Password', index: 'Password', hidden: true, width: 175, align: 'left', editable: true, edittype: 'password', editoptions: { maxlength: 20 }, editrules: { required: true, edithidden: true} },
{ name: 'FullName', index: 'FullName', width: 245, align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 100 }, editrules: { required: true} },
{ name: 'Email', index: 'Email', width: 247, align: 'left', formatter: emailFormatter, sortable: true, editable: true, edittype: 'custom', editoptions: { custom_element: mymailelem, custom_value: mymailvalue }, editrules: { required: true, email: true} },
{ name: 'IsActive', index: 'IsActive', width: 85, formatter: imgformatter, sortable: true, align: 'center',
editable: true, edittype: 'custom', editoptions: { custom_element: myelem, custom_value: myvalue }
},
{ name: 'role', index: 'role', width: 120, formatter: RoleCobFormatter, sortable: true, align: 'left' },
{ name: 'act', index: 'act', width: 55, align: 'center', sortable: false, formatter: 'actions',
formatoptions: {
keys: true,
editformbutton: true,
delbutton: true,
editOptions: {
url: '#Url.Action("UpdateUser")',
closeAfterEdit: true
},
delOptions: {
url: '#Url.Action("DeleteUser")'
}
}
}
],
pager: $('#jqgpUsers'),
rowNum: 10,
pginput: false,
rowList: [10, 20, 50, 100],
sortname: 'UserID',
sortorder: 'asc',
viewrecords: true,
height: 'auto',
loadComplete: function () {
if (pages[$('#jqgUsers').getGridParam('page')] != null) {
var selRows = pages[$('#jqgUsers').getGridParam('page')];
var i;
var limit = selRows.length;
for (i = 0; i < limit; i++) {
$('#jqgUsers').setSelection(selRows[i], true);
}
}
//-------Start Paging Style
var i, myPageRefresh = function (e) {
var newPage = $(e.target).text();
userGrid.trigger("reloadGrid", [{ page: newPage}]);
e.preventDefault();
};
//variables
var currentPage = this.p.page;
var startPage;
var totalPages = this.p.lastpage;
if (this.p.records == 0) {
totalPages = 0;
}
if (this.p.page - MAX_PAGERS <= 0) {
startPage = 1;
}
else {
startPage = this.p.page - MAX_PAGERS;
}
var lastPage;
if (this.p.page + MAX_PAGERS >= totalPages) {
lastPage = totalPages;
}
else {
lastPage = this.p.page + MAX_PAGERS;
}
$(userGrid[0].p.pager + '_center td.myPager').remove();
//---- Variables End
if (totalPages > 1) {
var pagerPrevTD = $('<td>', { "class": "myPager" }), prevPagesIncluded = 0,
pagerNextTD = $('<td>', { "class": "myPager" }), nextPagesIncluded = 0,
totalStyle = userGrid[0].p.pginput === false,
startIndex = totalStyle ? this.p.page - MAX_PAGERS * 2 : this.p.page - MAX_PAGERS;
for (i = startPage; i <= lastPage; i++) {
if (i <= 0) { continue; }
var link = $('<a>', { href: '#', click: myPageRefresh, "class": "Paging" });
if (i == this.p.page) { link.attr("class", "selected"); }
link.text(String(i));
if (i < this.p.page || totalStyle) {
pagerPrevTD.append(link);
prevPagesIncluded++;
} else {
if (nextPagesIncluded > 0 || (totalStyle && prevPagesIncluded > 0)) { pagerNextTD.append('<span>, </span>'); }
pagerNextTD.append(link);
nextPagesIncluded++;
}
}
if (prevPagesIncluded > 0) {
$(userGrid[0].p.pager + '_center td[id^="prev"]').after(pagerPrevTD);
}
if (nextPagesIncluded > 0) {
$(userGrid[0].p.pager + '_center td[id^="next"]').before(pagerNextTD);
}
}
else {
//$('#first_jqgpFlagger').unbind();
$('#first_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
//$('#prev_jqgpFlagger').unbind();
$('#prev_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
//$('#next_jqgpFlagger').unbind();
$('#next_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
//$('#last_jqgpFlagger').unbind();
$('#last_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
}
//-------End Paging Style
},
gridComplete: function () {
$.each(arrayIds, function (index, optionData) {
$.ajax({
url: '#Url.Action("GetRolesbyUserId", "Role")' + '/' + optionData.substring(4),
type: "GET",
cache: false,
async: false,
success: function (countiesJson) {
$.each(countiesJson, function (index, optionItem) {
$("#" + optionData + " option[value='" + optionItem.RoleID.toString() + "']").attr("selected", "selected");
});
}
});
if ($("#ddcl-" + optionData).length > 0) {
$("#ddcl-" + optionData).remove();
$("#ddcl-" + optionData + "-ddw").remove();
}
$("#" + optionData).dropdownchecklist({ emptyText: "Assign Roles" });
}); //End Each Loop
}
});
$('#jqgUsers').jqGrid('navGrid', '#jqgpUsers',
{ add: true, del: false, edit: false, search: false },
{ width: '250', closeAfterEdit: true, url: '#Url.Action("UpdateUser")' },
{ width: '250', closeAfterAdd: true, url: '#Url.Action("InsertUser")' },
{ width: '250', url: '#Url.Action("DeleteUser")' });
$('#CustomPanel').appendTo('.ui-jqgrid-hbox');
$(".ui-jqgrid-sortable").attr("style", "height: 32px");
$('#UserName1').blur(function () {
$('#jqgUsers').trigger("reloadGrid");
});
$('#FullName1').blur(function () {
$('#jqgUsers').trigger("reloadGrid");
});
$('#Email1').blur(function () {
$('#jqgUsers').trigger("reloadGrid");
});
$('#IsActive1').change(function () {
$('#jqgUsers').trigger("reloadGrid");
});
$('#btnClear').click(function () {
$('#UserName1').val('');
$('#FullName1').val('');
$('#Email1').val('');
$('#IsActive1 option:eq(0)').attr('selected', 'selected');
$('#jqgUsers').trigger("reloadGrid");
});
});
function emailFormatter(cellvalue) {
email = "<a href='mailto:" + cellvalue + "'>" + cellvalue + "</a>";
return email;
}
function mymailelem(value, options) {
var e1 = document.createElement("input");
e1.type = "text";
if (value != "") {
value = value.split('>')[1].split('<')[0];
}
e1.value = value;
z = document.createAttribute('class');
z.value = 'FormElement ui-widget-content ui-corner-all';
e1.setAttributeNode(z);
return e1;
}
function mymailvalue(elem, operation, value) {
if (value != undefined) {
value = value.split('>')[1].split('<')[0];
}
else {
value = '';
}
if (operation === 'get') {
return $(elem)[0].value;
} else if (operation === 'set') {
$(elem).val(value);
}
}
function imgformatter(cellvalue, options, rowObject) {
if (cellvalue == 'True') {
ActiveImage = "<img border='0' src='../../Content/images/tick.png' alt='' width='16px' height='16px' style='padding-top: 7px;' />";
}
else {
ActiveImage = "<img border='0' src='../../Content/images/cross.png' alt='' width='16px' height='16px' style='padding-top: 7px;' />";
}
return ActiveImage;
}
function RoleCobFormatter(cellvalue, options, rowObject) {
var id = "sel-" + options.rowId.toString();
arrayIds.push(id);
var retVal = roleDropDown.replace('_RoleID', id);
return retVal;
}
function myelem(value, options) {
var el = document.createElement("input");
el.type = "checkbox";
if (value.indexOf('tick') != -1) {
value = 'checked';
el.checked = 'checked';
}
else {
value = '';
el.checked = '';
}
return el;
}
function myvalue(elem, operation, value) {
if (value != undefined && value.indexOf('tick') != -1) {
value = 'checked';
}
else {
value = '';
}
if (operation === 'get') {
// return $(elem).find("input").val();
return $(elem).is(':checked');
} else if (operation === 'set') {
// $('input', elem).val(value);
// $('input', elem).attr('checked', value);
$(elem)[0].checked = value;
}
}
</script>
How can i display error message in Add/Edit Dialogue, please suggest.
the correct way will be to use some error HTML code in case of error. Instead of catching all exception in the server cage and returns return Json(false) you can throw exception which contains an error message. You can use [HandleJsonException] for example (see the answer) to encode any exceptions as simple JSON response with System.Net.HttpStatusCode.InternalServerError as HttpContext.Response.StatusCode. In the way you can post detailed error information to the jqGrid.
To decode the error information you can use errorTextFormat method in the same way as in decodeErrorMessage function from the same answer.
If you follow the way you will don't need to use any CheckUserName method. instead of that you can use method like .Save(user). The exception will be thrown automatically if needed. If you want to display more detailed error information you can catch for example SqlException, decode the information and produce another exception in the text of which you just includes information from the Server, Procedure, LineNumber, Message and so on properties of SqlException.