jqgrid does not fire when the ENTER key gets pressed - jqgrid

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

Related

page not loading on button click but works on link button in jqGrid in MVC

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.

how create dynamic multiple jqgrid some page

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>

Jqgrid columns are not editable in firefox pl help me

The jqgrid is working fine in chrome but it is not working fine in Firefox, in Firefox I am not able to edit the rows, even drop down is not working, if I use tab then only it is working fine, here is my code:
var l = $("#variablesGrid");
l.jqGrid({
datatype: "local",
data: e,
colNames: ["Data Type", "Is not Array", "Field Name", "Action"],
colModel: [{
name: "dataType",
index: "dataType",
width: 50,
editable: true,
edittype: "select",
editoptions: {
value: r
},
align: "left"
}, {
name: "isArray",
index: "isArray",
width: 17,
editable: true,
formatter: "checkbox",
edittype: "checkbox",
editoptions: {
value: "true:false"
},
align: "center"
}, {
name: "fieldName",
index: "fieldName",
width: 40,
editable: true,
align: "left",
editrules: {
custom: true,
custom_func: f
}
}, {
name: "act",
index: "act",
width: 10,
sortable: false
}],
rowNum: 1e5,
pager: "#variablesPager",
gridview: true,
rownumbers: true,
sortname: "invdate",
viewrecords: true,
sortorder: "desc",
caption: "Variables",
editurl: "clientArray",
width: 900,
height: 250,
loadComplete: function () {
var e = this;
setTimeout(function () {
updatePagerIcons(e);
enableTooltips(e)
}, 0)
},
gridComplete: function () {
var e = jQuery(o).jqGrid("getDataIDs");
for (var t = 0; t < e.length; t++) {
var r = e[t];
ce = '<div title="" style="float:left;margin-left:5px;" class="ui-pg-div ui-inline-del" id="jDeleteButton_12" onclick="BPMProcessPropertiesModule.deleteGridRow(\'' + r + "','" + n + '\');" onmouseover="jQuery(this).addClass(\'ui-state-hover\');" onmouseout="jQuery(this).removeClass(\'ui-state-hover\');" data-original-title="Delete selected row"><span class="ui-icon ui-fa fa-trash"></span></div>';
jQuery(o).jqGrid("setRowData", e[t], {
act: ce
})
}
},
onSelectRow: function (e) {
if (s === false) {
if (e !== t) {
if(t === undefined){
t = e;
}
var r = jQuery(o).jqGrid("getCell", t, "fieldName");
if (r !== false && r != "undefined") {
if (r.indexOf('name="fieldName"') > 0) {
r = $("#" + t + "_fieldName").val();
n = false;
if (r === "" || r === " " || MDBPMUtils.hasSpaces(r)) {
n = true;
l.jqGrid("saveRow", t);
$("#" + t + "_fieldName").focus();
jQuery("#variablesGrid").jqGrid("setSelection", t)
}
}
}
}
}
if (n === false) {
if (e !== t) {
if (t) {
l.jqGrid("saveRow", t)
}
t = e
}
l.jqGrid("editRow", e, true);
return true
}
}
});

Sorting icon not updating on setting the sortorder

I am trying to change the sorting order of jqGrid by using this code:
jQuery('#id').setGridParam({sortorder:"desc"}).trigger("reloadGrid");
It changes the sortorder of the table but the Sorting Icon of the table is not changing as per the order. In onSortCol i'm sorting the column which actually sort the column. But when i use the above piece of code to set the sortorder, the sortorder is set but the sort icon still shows the previous sortorder.
_table.jqGrid({
datatype: 'local', // disable initial autoload. this will be when load function is called "json",
altRows: true,
altclass : 'AltRowClass',
gridView: true,
width:850,
height:"auto",
rowheight: 75,
align: 'center',
treeGrid: false,
loadonce:true,
ExpandColumn: 'name',
loadtext : 'Currently updating',
mtype : 'POST',
colNames: ['MSISDN','IMSI','Last name','First name','Device type','CE Index','Customer lifetime value'],
colModel: [
{ name: 'MSISDN', align: 'center', hidden: false, sortable: false,formatter: maskingColumn},
{ name: 'IMSI', align: 'center', hidden: false, sortable: false,formatter: maskingColumn},
{ name: 'LastName', align: 'center', hidden: false, sortable: false},
{ name: 'FirstName', align: 'center', hidden: false, sortable: false},
{ name: 'DeviceType', align: 'center', hidden: false, sortable: false,formatter: columnData},
{ name: 'CEIndex', align: 'center', hidden: false, sortable: true, sorttype: 'int'},
{ name: 'CustomerLifetimeValue', align: 'center', hidden: false, sortable: false}
],
sortname: 'CEIndex',
sortorder: 'desc',
loadComplete: function(data)
{
var rowCount = _table.jqGrid('getGridParam', 'records');
if (rowCount > 5) {
_table.parents("div.ui-jqgrid-bdiv").css({'max-height':'300px'});
_table.closest(".ui-jqgrid-bdiv").css({'overflow-y':'auto'}).css({'overflow-x':'hidden'});
}
if (rowCount != 0) {
_table.parents().find('.ui-jqgrid-view').first().show();
}
if (rowCount <= rowsNum) {
utils.find('cei-drill-customer-detail-showmore').hide();
} else {
utils.find('cei-drill-customer-detail-showmore').show();
}
_table.trigger("reloadGrid");
} ,
onSortCol: function (data, status, xhr) {
if (xhr == 'asc') {
var postData = this.p.postData.jsonRequest.replace('Top','Bottom');
actionInputObjectExportCustDrilldown.parameters.requestQuery = actionInputObjectExportCustDrilldown.parameters.requestQuery.replace('Top','Bottom');
var postDataVar = {
operation : 'drillDownLevel1',
drillLevel1 : "drilldown",
jsonRequest : postData
};
_this.load(postDataVar);
} else if (xhr == 'desc') {
var postData = this.p.postData.jsonRequest.replace('Bottom','Top');
actionInputObjectExportCustDrilldown.parameters.requestQuery = actionInputObjectExportCustDrilldown.parameters.requestQuery.replace('Bottom','Top');
var postDataVar = {
operation : 'drillDownLevel1',
drillLevel1 : "drilldown",
jsonRequest : postData
};
_this.load(postDataVar);
}
},
beforeProcessing : function(data, status, xhr) {
jQuery('div#jqgh_' + prefix + '-cei-dd-customer-details-table_CustomerLifetimeValue.ui-jqgrid-sortable').text("Customer Lifetime Value(" + filterValuesHl.currency + ")");
if (data.queryError != null || !data.rows || data.rows.length == 0) {
utils.find('cei-drill-customer-detail-ExportShowMore').hide();
utils.find('div-for-export-customer').hide();
var noError = utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data");
if (data.queryError != null) {
noError.text("Error in portlet: " + data.queryError);
} else {
noError.html("<strong>No Data Available</strong>");
}
noError.show();
return false;
} else {
utils.find('cei-drill-customer-detail-ExportShowMore').show();
utils.find('div-for-export-customer').show();
utils.find('cei-drill-customer-detail-showmore').show();
//Hiding the columns which has no data in all the rows.
hideColumns(data);
//Setting CSV Data
csvData = data;
}
},
beforeRequest : function() {
_table.parents().find('.ui-jqgrid-view').first().hide();
utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data").hide();
},
loadError : function(xhr, st, err) {
utils.find('cei-drill-customer-detail-ExportShowMore').hide();
utils.find('div-for-export-customer').hide();
var noError = utils.find('cei-customerDetails-div').parent().find(".cei-customer-details-dd-no-data");
noError.html("<html>Error connecting portlet: " + err + "</strong>");
noError.show();
}
});
You can try following code where id is your column name.
$('#grid').jqGrid('setGridParam', {sortorder: 'desc'});
$('#grid').jqGrid('sortGrid', 'id');

how to display error message in Add/Edit dialogue of jqGrid while checking duplicate username?

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.

Resources