Related
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>
Using Datatables, and the fnReloadAjax plugin (see below), I am trying to reload the table's data from a server-side script using the following code:
$.fn.dataTableExt.oApi.fnReloadAjax = function(oSettings, sNewSource, fnCallback, bStandingRedraw) {
if (sNewSource !== undefined && sNewSource !== null) {
oSettings.sAjaxSource = sNewSource;
}
// Server-side processing should just call fnDraw
if (oSettings.oFeatures.bServerSide) {
this.fnDraw();
return;
}
this.oApi._fnProcessingDisplay(oSettings, true);
var that = this;
var iStart = oSettings._iDisplayStart;
var aData = [];
this.oApi._fnServerParams(oSettings, aData);
oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) {
/* Clear the old information from the table */
that.oApi._fnClearTable(oSettings);
/* Got the data - add it to the table */
var aData = (oSettings.sAjaxDataProp !== "") ?
that.oApi._fnGetObjectDataFn(oSettings.sAjaxDataProp)(json) : json;
for (var i = 0; i < aData.length; i++) {
that.oApi._fnAddData(oSettings, aData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw();
if (bStandingRedraw === true) {
oSettings._iDisplayStart = iStart;
that.oApi._fnCalculateEnd(oSettings);
that.fnDraw(false);
}
that.oApi._fnProcessingDisplay(oSettings, false);
/* Callback user function - for event handlers etc */
if (typeof fnCallback == 'function' && fnCallback !== null) {
fnCallback(oSettings);
}
}, oSettings);
};
$(document).ready(function() {
$('#reloadDataBtn').click(function() {
$('#myTable').fnReloadAjax('mySource2.php');
});
$("#myTable").dataTable({ bSort: true,
"bProcessing": true,
"sAjaxSource": 'mySource1.php',
bAutoWidth: true,
"iDisplayLength": 5, "aLengthMenu": [5, 10, 25, 50, 100],
"sPaginationType": "full_numbers",
"aoColumnDefs": [{ "bSortable": false, "aTargets": [-1, 0]}]
});
});
But I still get the fnReloadAjax is not a function JS error. What am I doing wrong?
In verstion 1.10 of DataTable plugin, function fnReloadAjax is deprecated, now you need use api().ajax.reload() instead:
$(document).ready(function() {
var datatable = $('#calls_list_table').dataTable({
"iDisplayLength": 10,
"processing": true,
"serverSide": true,
"ajax": {
"url": "/calls/data/",
"type": "POST"
}
});
$('button').click(function() {
// use it instead of fnReloadAjax
datatable.api().ajax.reload();
});
});
This is because you address an element returned by jQuery, not the dataTable object itself.
Do this instead :
var dataTable; //reference to your dataTable
$('#reloadDataBtn').click(function() {
dataTable.fnReloadAjax('mySource2.php');
//NOT
//$('#myTable').fnReloadAjax('mySource2.php');
});
dataTable = $("#myTable").dataTable({
bSort: true,
"bProcessing": true,
"sAjaxSource": 'mySource1.php',
bAutoWidth: true,
"iDisplayLength": 5, "aLengthMenu": [5, 10, 25, 50, 100],
"sPaginationType": "full_numbers",
"aoColumnDefs": [{ "bSortable": false, "aTargets": [-1, 0]}]
});
Now fnReloadAjax() will be called proplerly.
I need help about a kendo grid,
I call a webservice to fill a datasource of the grid. It seems to work fine, but the data are not displayed in the grid.
The webservice call returns 7 records, and in the grid there are 7 rows, but they are empty.
this is the code:
var mime_charset = "application/json; charset=utf-8";
var serverSelectReturnsJSONString = true;
var model_definition = {
id: "ID",
fields: {
customer_id: { type: "number" },
name_customer: { type: "string" },
address_customer: { type: "string" }
}
}
$(document).ready(function () {
var ds = createJSONDataSource();
$("#grid").kendoGrid({
selectable: true,
theme: "metro",
dataSource: ds,
scrollable: true,
pageable: true,
// height: 300,
toolbar: ["save", "cancel"],
columns: ["ID", "Nome", "Indirizzo"],
editable: true
});
ds.read();
});
and this is the function for filling the datasource:
function createJSONDataSource() {
var dataSource = new kendo.data.DataSource({
severFiltering: true,
serverPaging: true,
PageSize: 15,
//batch: true,
transport: {
autoSync: true,
read: {
type: "POST",
url: "WebServices/GetDataTest.asmx/getCustList",
dataType: "json",
contentType: mime_charset
}
},
schema: {
data: function (data) {
if (data) {
if (serverSelectReturnsJSONString)
return $.parseJSON(data.d);
else
return data.d;
}
},
total: function (result) {
if (!result) return 0;
var xxx = result.d;
if (xxx == null) {
return result.length || 0;
}
if (result.d) {
if (serverSelectReturnsJSONString) {
var data = $.parseJSON(result.d);
return data.length || 0;
}
else {
return result.d.TotalRecords || result.d.length || result.length || 0;
}
}
},
model: model_definition
}
});
dataSource.options.schema.parse = function (dataJ) {
var data;
data = $.parseJSON(dataJ.d);
if (data) {
$.each(data, function (i, val) {
$.each(model_definition.fields, function (j, col) {
if (col.type == "date" || col.type == "datetime") {
val[j] = toDate(val[j]);
}
})
});
var ret = { d: JSON.stringify(data) };
return ret;
}
}
dataSource.reader.parse = dataSource.options.schema.parse;
return dataSource;
}
Your columns definition is not correct, it is an array but of objects (not strings). Check documentation here. If should be something like:
columns: [
{ field: "ID" },
{ field: "Nome" },
{ field: " "Indirizzo" }
],
I'm using jqgrid in an ASPNET MVC4 project with WebApi (REST), Entity Framework 5 using Unit Of Work and Repository patterns.
My problem is that I see the data flowing as json to the browser and I see three rows in the grid, but those rows are empty, and the data is not shown (three empty rows in the grid).
This is method to get the data in the WebApi controller:
public dynamic GetGridData(int rows, int page, string sidx, string sord)
{
var pageSize = rows;
var index = sidx;
var order = sord;
var categories = Uow.Categories.GetAll().OrderBy(t => (string.IsNullOrEmpty(index) ? "Id" : index) + " " + (order ?? "desc"));
var pageIndex = Convert.ToInt32(page) - 1;
var totalRecords = categories.Count();
var totalPages = (int)Math.Ceiling((float) totalRecords / (float) pageSize);
var categoriesPage = categories.Skip(pageIndex * pageSize).Take(pageSize).ToList();
return new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from category in categoriesPage
select new
{
id = category.Id.ToString(),
cell = new string[]
{
category.Id.ToString(),
category.Name,
category.Description
}
}).ToArray()
};
}
This is the json received in the browser
{
"total": 1,
"page": 1,
"records": 3,
"rows": [{
"id": "1",
"cell": ["1", "Category 1", null]
}, {
"id": "3",
"cell": ["3", "Category 3", "asAS"]
}, {
"id": "4",
"cell": ["4", "Category 4", null]
}]
}
This is the .js file with jqgrid
jQuery("#ajaxGrid").jqGrid({
url: $("#ServiceUrl").val(),
datatype: "json",
jsonReader: { repeatitems: false, id: "Id" },
colNames: ['Id', 'Name', 'Description'],
colModel: [
{ name: 'id', editable: true, sortable: true, hidden: true, align: 'left' },
{ name: 'name', editable: true, sortable: true, hidden: false, align: 'left' },
{ name: 'description', editable: true, sortable: true, hidden: false, align: 'left' }
],
mtype: 'GET',
rowNum: 15,
pager: '#ajaxGridPager',
rowList: [10, 20, 50, 100],
caption: 'List of Categories',
imgpath: $("#ServiceImagesUrl").val(),
altRows: true,
shrinkToFit: true,
viewrecords: true,
autowidth: true,
height: 'auto',
error: function(x, e)
{
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
function updateDialog(action) {
return {
url: $("#ServiceUrl").val(),
closeAfterAdd: true,
closeAfterEdit: true,
afterShowForm: function (formId) { },
modal: true,
onclickSubmit: function (params) {
var list = $("#ajaxGrid");
var selectedRow = list.getGridParam("selrow");
params.url += "/" + list.getRowData(selectedRow).Id;
params.mtype = action;
},
width: "300",
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (data) {
delete data.oper;
return JSON.stringify(data);
}
};
}
jQuery("#ajaxGrid").jqGrid(
'navGrid',
'#ajaxGridPager',
{
add: true,
edit: true,
del: true,
search: false,
refresh: false
},
updateDialog('PUT'),
updateDialog('POST'),
updateDialog('DELETE')
);
BTW, If I want to return jqGridData instead the dynamic, How should I do it? Did is showing empty rows as well:
public class jqGridData<T> where T : class
{
public int page { get; set; }
public int records { get; set; }
public IEnumerable<T> rows { get; set; }
public decimal total { get; set; }
}
public jqGridData<Category> GetGridData(int rows, int page, string sidx, string sord)
{
var pageSize = rows;
var index = sidx;
var order = sord;
var categories = Uow.Categories.GetAll().OrderBy(t => (string.IsNullOrEmpty(index) ? "Id" : index) + " " + (order ?? "desc"));
var pageIndex = Convert.ToInt32(page) - 1;
var totalRecords = categories.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var categoriesPage = categories.Skip(pageIndex * pageSize).Take(pageSize);
return new jqGridData<Category>
{
page = page,
records = totalRecords,
total = totalPages,
rows = categoriesPage
};
}
Thanks in advance!!! Guillermo.
Ok, I can't believe it, but it was the case in the name of the columns. First letter should be capitalized as it's capitalized in the data sent.
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.