Related
I used full calendar in my CodeIgniter project to manage events. All other parts of the project are working properly. But the calendar output is look like this :
The dates are collapsed in the output. Relevant JavaScript for calendar as follows :
<Script>
$(document).on('click', '.month_select', function() {
var month = $(this).data('month');
var moment = $('#calendar').fullCalendar('getDate');
var currentMonth = moment.format('YYYY') + '-' + month + '-' + 10;
$('#calendar').fullCalendar('gotoDate', currentMonth);
});
$(function() {
$('#viewed,#new,#issued,#recieved,#request,#return, #requestProofs').on('ifChanged', function(event) {
$('#calendar').fullCalendar('refetchEvents');
});
var date = new Date();
var d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$('#calendar').fullCalendar({
aspectRatio: 1.7,
firstDay: 1,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay',
},
allDay: true,
buttonText: {
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
events: {
url: "<?= site_url('document/getImprestDocuments') ?>",
data: function() {
return {
viewed: $('#viewed').is(':checked'),
new: $('#new').is(':checked'),
issued: $('#issued').is(':checked'),
recieved: $('#recieved').is(':checked'),
request: $('#request').is(':checked'),
requestProofs: $('#requestProofs').is(':checked'),
return: $('#return').is(':checked'),
};
},
error: function() {
$('#script-warning').show();
}
},
eventClick: function(event) {
if (event.url) {
window.open(event.url);
event.color = event.default_color;
$('#calendar').fullCalendar('updateEvent', event);
return false;
}
},
eventRender: function(event, element) {
},
loading: function(bool) {
if (bool) {
$(this).block({
message: '<div class="loading-message"><h3 style="margin: 5px;"><img style="width:35px;" src="<?= base_url() ?>public/dist/img/ring-alt.gif" > Processing...</h3></div>',
cenrerY: true,
css: {
border: '3px solid rgb(221, 75, 57)'
}
});
} else {
$(this).unblock();
}
}
});
});
$(document).ready(function() {
var table = $("#request_imprest").DataTable({
"order": [
[1, "desc"]
],
columnDefs: [{
sortable: false,
"class": "index",
targets: 0
}]
})
table.on('order.dt search.dt', function() {
table.column(0, {
search: 'applied',
order: 'applied',
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
})
</script>
url: "<?= site_url('document/getImprestDocuments') ?>" is also working fine. What may be going wrong ? Can anyone help ?
Requirement How to excel export hidden fields using kendoui grid
By using kendo editor i have implemented grid and i want to export hidden field using Excel export in kendo ui Grid Here I want to export Id field in Excel which is hidden here
My main moto is to export the hidden columns using excel export
<div id='grid-container'>
<div id='student-details-grid'
data-role='grid'
data-groupable='true'
data-sortable='true'
data-toolbar=['excel']
data-excel="{fileName: 'StudentDetails.xlsx', proxyURL: '/save', filterable: true, allPages: true}"
data-height='450px'
data-pageable="[
{'refresh':'true' },
{ 'pageSizes':'true'},
{'buttonCount':'5'}
]"
data-bind='source:gridDataSource'
data-columns="[{'field':'Id','title':'Id'},{'field':'Name','title':'Name'},{'field':'FatherName','title':'FatherName'},{'field':'Email','title':'Email'},{'field':'Address','title':'Address'},{'field':'ContactNo','title':'ContactNo'}]"
style="height: 550px">
</div>
</div>
<script type="text/javascript">
var viewModel = '';
$(document).ready(function (e) {
viewModel = kendo.observable({
gridDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Home/GetStudents",
dataType: "json"
}
},
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, nullable: true },
Name: { validation: { required: true } },
FatherName: { type: "text", validation: { required: true, min: 1 } },
Email: { type: 'email', validation: { min: 0, required: true } },
Address: { type: "text", validation: { min: 0, required: true } },
ContactNo: { type: 'text', validation: { min: 0, required: true } },
}
},
parse: function (data) {
debugger
if (!data.success && typeof data.success !== 'undefined') {
gridDataSource.read();
}
if (data.success) {
viewModel.gridDataSource.read();
}
return data;
}
}
}),
});
kendo.bind($("#grid-container"), viewModel);
});
</script>
*Global variable
isExport = false;
data-bind="source: dataSource,events:{excelExport : onExcelExport}"
onExcelExport: function (e) {
var sheet = e.workbook.sheets[0];
for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
var row = sheet.rows[rowIndex];
for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
if (cellIndex === 6 || cellIndex === 8 || cellIndex === 20)
row.cells[cellIndex].format = "HH:mm"
}
}
var gridcolumn = e.sender.columns;
if (!isExport) {
$.each(gridcolumn, function (index, value) {
if (value.hidden)
e.sender.showColumn(index);
else if (value.hidden === false)
e.sender.hideColumn(index);
e.sender.hideColumn(0);
});
e.preventDefault();
isExport = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
$.each(gridcolumn, function (index, value) {
if (value.hidden === false)
e.sender.hideColumn(index);
else
e.sender.showColumn(index);
});
isExport = false;
}
},
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>
I am using a Kendo UI grid, which looks like this:
function refreshGrid()
{
$(".k-pager-refresh.k-link").click();
}
var editWindow;
var fields= {FullName: {type: "string"}, Email: {type: "string"}, LogCreateDate: {type: "date"}};
var gridColumns =
[{
width: 90,
command: {
name: "edit",
text: "Edit",
click: function(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
editWindow = $("#edit").kendoWindow({
title: "Edit User",
modal: true,
visible: false,
resizable: false,
width: 800,
height: 400,
content: 'myediturl' + dataItem.ID
});
editWindow.data("kendoWindow").center().open();
return false;
}
}
},
{
width: 90,
command: {
name: "delete",
text: "Delete",
click: function(e) {
//alert(this.dataItem($(e.currentTarget).closest("tr")).ID);
var id = this.dataItem($(e.currentTarget).closest("tr")).ID;
if (confirm("Are you sure you want to delete this user?"))
{
$.ajax({
type: 'POST',
url: '#Url.Action("deleteuser","admin",null, "http")' + "/" + this.dataItem($(e.currentTarget).closest("tr")).ID,
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
}
}
},
{
field: "FullName",
title: "Full Name",
type: "string"
},
{
field: "Email",
title: "Email",
type: "string"
},
{
field: "LogCreateDate",
title: "Created",
type: "date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
}];
//getSorts the columns of the grid
function getColumns() {
//Parsing the set of columns into a more digestable form
var columns = "";
for (var col in gridColumns) {
if (!!gridColumns[col].field)
{
if (columns.length > 0) {
columns += ";";
}
columns += gridColumns[col].field + "," + gridColumns[col].type;
}
}
return columns;
}
function getSorts(sortObject) {
if (!(sortObject)) {
return "";
}
//Getting the row sort object
var arr = sortObject;
if ((arr) && (arr.length == 0)) {
return "";
}
//Parsing the sort object into a more digestable form
var columnSet = getColumns();
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in gridColumns) {
if (gridColumns[col].field === arr[index].field) {
type = gridColumns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
var grid;
$(function () {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "mydatasourceurl",
type: "POST",
},
parameterMap: function (data, type) {
data.filters = JSON.stringify(data.filter);
data.columns = JSON.stringify(getColumns());
data.sorts = JSON.stringify(getSorts(data.sort));
console.log(data);
return data;
}
},
schema: {
fields: fields,
data: "Data",
total: "Total"
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
toolbar: [{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}],
height: 392,
groupable: false,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: gridColumns
});
grid = $("#grid").data("kendoGrid");
});
My create toolbar action is not triggered on click. How can I resolve this problem, is Kendo UI able to handle toolbar click events? The best solution I came up with looks like this:
$(".k-button.k-button-icontext.k-grid-add").click(function () {
//If the window doesn't exist yet, we create and initialize it
if (!grids[gridContainerID].addWindow.data("kendoWindow")) {
grids[gridContainerID].addWindow.kendoWindow({
title: "Add " + entityName,
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: addUrl
});
}
//Otherwise we just open it
else {
grids[gridContainerID].addWindow.data("kendoWindow").open();
}
//Centralizing and refreshing to prepare the layout
grids[gridContainerID].addWindow.data("kendoWindow").center();
grids[gridContainerID].addWindow.data("kendoWindow").refresh();
return false;
});
Thanks in advance.
Instead of using that complex selector use the one that Kendo UI creates from name:
toolbar: [
{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}
],
and then:
$(".k-grid-Add", "#grid").bind("click", function (ev) {
// your code
alert("Hello");
});
In kendogrid docs here shows that there is no click configuration for grid toolbar buttons like grid.colums.commands.
To solve this problem you can reference following steps:
create a template for toolbar
<script id="grid_toolbar" type="text/x-kendo-template">
<button class="k-button" id="grid_toolbar_queryBtn">Query</button>
</script>
apply tempate to toolbar
toolbar:[{text:"",template: kendo.template($("#grid_toolbar").html())}]
add event listener to button
$("#grid_toolbar_queryBtn").click(function(e) {
console.log("[DEBUG MESSAGE] ", "query button clicked!");
});
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.