Kendo Gantt Timeline in 30 minute increments? - asp.net-mvc

I am using the Kendo Gantt chart with ASP.NET Core MVC, and I would like to get the Day view timeline to show in 30 minute increments vs. 1 hour increments. The working hours I'm trying to display for each day are 7:00 AM to 3:30 PM, but I cannot get that 3:30 PM end of day to display.
Here is an example of getting a time header template using the jquery kendo gantt chart
<div id="gantt"></div>
<script>
$("#gantt").kendoGantt({
dataSource: [{
id: 1,
orderId: 0,
parentId: null,
title: "Task1",
start: new Date("2014/6/17 9:00"),
end: new Date("2014/6/17 11:00")
}],
views: [
{ type: "day", timeHeaderTemplate: kendo.template("#=kendo.toString(start, 'T')#") },
{ type: "week" },
{ type: "month" }
]
});
</script>
However, I can't figure out how get that template to show the 30 minute increments, or if there is a different way to accomplish this. Essentially, I want it to look like the Kendo Scheduler Timeline view shown here:

I opened a support ticket with Telerik and got an answer that while there is no built-in way to do this with the Gantt component, one way to implement would be to create a custom view as demonstrated here: https://docs.telerik.com/kendo-ui/controls/scheduling/gantt/how-to/creating-custom-view
Custom view example code:
<div id="gantt"></div>
<script type="text/javascript">
var gantt;
$(function StartingPoint() {
kendo.ui.GanttCustomView = kendo.ui.GanttView.extend({
name: "custom",
options: {
yearHeaderTemplate: kendo.template("#=kendo.toString(start, 'yyyy')#"),
quarterHeaderTemplate: kendo.template("# return ['Q1', 'Q2', 'Q3', 'Q4'][start.getMonth() / 3] #"),
monthHeaderTemplate: kendo.template("#=kendo.toString(start, 'MMM')#")
},
range: function(range) {
this.start = new Date("01/01/2013");
this.end = new Date("01/01/2016");
},
_generateSlots: function(incrementCallback, span) {
var slots = [];
var slotStart = new Date(this.start);
var slotEnd;
while (slotStart < this.end) {
slotEnd = new Date(slotStart);
incrementCallback(slotEnd);
slots.push({ start: slotStart, end: slotEnd, span: span });
slotStart = slotEnd;
}
return slots;
},
_createSlots: function() {
var slots = [];
slots.push(this._generateSlots(function(date) { date.setFullYear(date.getFullYear() + 1); }, 12));
slots.push(this._generateSlots(function(date) { date.setMonth(date.getMonth() + 3); }, 3));
slots.push(this._generateSlots(function(date) { date.setMonth(date.getMonth() + 1); }, 1));
return slots;
},
_layout: function() {
var rows = [];
var options = this.options;
rows.push(this._slotHeaders(this._slots[0], kendo.template(options.yearHeaderTemplate)));
rows.push(this._slotHeaders(this._slots[1], kendo.template(options.quarterHeaderTemplate)));
rows.push(this._slotHeaders(this._slots[2], kendo.template(options.monthHeaderTemplate)));
return rows;
}
});
gantt = new kendo.ui.Gantt($("#gantt"),
$.extend({
columns: [
{ field: "id", title: "ID", sortable: true, editable: false, width: 30 },
{ field: "title", title: "Title", sortable: true, editable: true, width: 100 },
{ field: "start", title: "Start Time", sortable: true, editable: true, format: "{0:MM/dd/yyyy HH:mm}", width: 100 },
{ field: "end", title: "End Time", sortable: true, editable: true, format: "{0:MM/dd/yyyy HH:mm}", width: 100 }
],
views: [
"week",
{ type: "kendo.ui.GanttCustomView", title: "Quaterly", selected: true }
],
listWidth: 500,
dataBound: function() {
var height = this.timeline.view().header.height();
this.list.thead.find('tr').css('height',height);
},
dataSource: {
data: [{ id: 1, parentId: null, percentComplete: 0.2, orderId: 0, title: "foo", start: new Date("05/05/2014 09:00"), end: new Date("06/06/2014 10:00") },
{ id: 2, parentId: null, percentComplete: 0.4, orderId: 1, title: "bar", start: new Date("07/06/2014 12:00"), end: new Date("08/07/2014 13:00") }]
},
dependencies: {
data: [
{ id: 1, predecessorId: 1, successorId: 2, type: 1 }
]
}
}, {})
);
});
</script>

Related

Call knockout method inside kendo grid

I have simple kendo UI grid
$("#Grid").kendoGrid({
dataSource: {
serverPaging: true,
transport: {
read: "Course/Read",
dataType: "json"
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
pageSize: 10
},
pageable: true,
columns:
[
{ field: "CourseName", title: "Name", width: 100 },
{ field: "SpecialtyName", title: "Specialty", width: 100, filterable: false },
{ title: "Edit", template: '<span class="EditIcon"><i data-bind="click:Edit(#: Id#)" class="fa fa-edit"></i></span>', width: 50 },
]
});
the problem is when I am using:
data-bind="click:Edit(#: Id#)"
when click on edit calling function not work inside kendo grid notice that both the grid and function inside knockout viewmodel
function viewmodel() {
var self = this;
self.Load = function () {
$("#Grid").kendoGrid({
dataSource: {
type: "aspnetmvc-ajax",
serverPaging: true,
transport: {
read: "Course/Read",
dataType: "json"
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
pageSize: 10
},
pageable: true,
columns:
[
{ field: "CourseName", title: "Name", width: 100 },
{ field: "SpecialtyName", title: "Specialty", width: 100, filterable: false },
{ title: "Edit", template: '<span class="EditIcon"><i data-bind="click:Edit(#: Id#)" class="fa fa-edit"></i></span>', width: 50 },
]
});
}
self.Load();
self.Edit= function (Id) {
////////my code////////
}
}
everything work fine the binding retrieve data, extra except call knockout method inside kendo grid, appreciate any help thanks.
if anyone looking for answer or open this post, this is not related to kendo, this is because the grid render rows after knockout binding done, so you can take viewmodel object in temp var in javascript and use it like tempvar.callfunction().

Kendo grid sending date in wrong format

it is kendoui grid working against webapi (.net mvc 4 project)
the kendoGrid part in my js file:
$("#eventsgrid").kendoGrid({
dataSource: {
transport: {
read: { url: "/Webapi/V2/.../events", type: "GET" },
update: { url: "/Webapi/V2/.../events", type: "PUT" },
create: { url: "/Webapi/V2/.../events", type: "POST" },
destroy: { url: "/Webapi/V2/.../events", type: "DELETE" }
},
pageSize: 10,
schema: {
model: {
id: "eventId",
fields: {
eventId: { type: "number", editable: false, nullable: true },
eventCode: { type: "string" },
eventLocation: { type: "string" },
clientId:{ type: "string" },
startDate:{ type: "date" },
endDate: { type: "date" }
}
}
}
},
columns: [
{ field: 'eventId', title: 'ID', width: '50px', filterable: true },
{ field: 'eventCode', title: 'Code', width: '80px', filterable: true },
{ field: 'eventLocation', title: 'Location', width: '150px', filterable: true },
{ field: 'clientId', title: 'Client', width: '80px', filterable: true },
{ field: 'startDate', title: 'Start', width: '80px', format: "{0:MM/dd/yyyy}", filterable: { ui: "datepicker" } },
{ field: 'endDate', title: 'End', width: '80px', format: "{0:MM/dd/yyyy}", filterable: { ui: "datepicker" } },
{ command: [{ id: "edit", name: "edit", text: "Edit" }, { id: "destroy", name: "destroy", text: "Delete", width: "30px" }, { text: 'Details', click: gotouser }], title: "&nbsp", width: "240px" }
],
sortable: true,
editable: "popup",
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
},
toolbar: [{ name: "create", text: "Add new Event" }],
pageable: { pageSizes: true | [10, 20, 30] }
});
the problem is: when i edit a record, or post a new one, the value i receive in my mvc controller for any of the date fields, is null.
when i check in my chrome tools, see what the grid sends to the controller (when you hit update in the popup), like this:
clientId: 1
startDate: Tue Jan 20 2015 00:00:00 GMT-0500 (Eastern Standard Time)
endDate: Thu Jan 22 2015 00:00:00 GMT-0500 (Eastern Standard Time)
logo: abcsd.jpg
featured: 4
obviously the date format is wrong, and i suppose that is why the controller does not see it as a date, the conversion/binding fails, and it gives me null.
How do i make it send a different format, like mm/dd/yyyy ? isn't that covered by the format definitions in the columns array?
You can try to use parameterMap function. Look at kendo parameterMap documentation.
Similar to this:
parameterMap: function (data, operation) {
if (operation != "read") {
var parsedDate = kendo.parseDate(data.startDate, "MM/dd/yyyy");;
data.startDate = parsedDate;
return data;
}
}
For kendo parsing dates look at kendo parseDate
in the parameterMap use:
var parsedDate = kendo.toString(data.startDate, "MM/dd/yyyy")
the kendo.parseDate function takes a string as a parameter
OK, I followed Dmitriy's line, and was able to make it work. so for future generations, here is what you need to add to your js:
update: {
url: "/Webapi/..../events",
dataType: "json",
type: "PUT",
data: function (data) {
data.startDate = kendo.toString(data.startDate, "yyyy-MM-dd");
data.endDate = kendo.toString(data.endDate, "yyyy-MM-dd");
// repeat for all your date fields
return data;
}
},
// same thing for your 'create'.
// Sorry, look like a bit of 'Repeat yourself', but at least it's working.
So again, big thanks to Dimitriy!

How to open custom edit dialog on click of inline image icon?

I need inline image buttons for EDIT and DELETE functionality.
But, I don't need default inline editing or inbuilt dialog popup as , my design is as follow.
add/edit form is appear first and then, below that section, - grid is appearing.
On click of - row inline "Edit" image button , need to populate row data on above form.
To achieve this, on click of edit image button, I need to have javascript function call along with row data object.
How to achieve this ? Can any one share me the column code and function which can allow me to achieve this ?
Below is jqgrid stuff:
$('#CategoriesGrdList').jqGrid({
ajaxGridOptions: {
error: function () {
$('#CategoriesGrdList')[0].grid.hDiv.loading = false;
alert('An error has occurred.');
}
},
url: '#Url.Action("GetAllCategoriesList", "Categories")/' + 0,
gridview: true,
autoencode: true,
postData: { categoryId: 1 },
datatype: 'json',
jsonReader: { root: 'List', page: 'Page', total: 'TotalPages', records: 'TotalCount', repeatitems: false, id: 'Id' },
mtype: 'GET',
colNames: ['Id', 'Code', 'Description', 'IsActive', "actions"],
colModel: [
{ name: 'Id', index: 'Id', hidden: true, key: true },
{ name: 'Code', index: 'Code', width: 170 },
{ name: 'Description', index: 'Description', width: 170 },
{ name: 'IsActive', index: 'IsActive', width: 170 },
{
name: 'actions', index: 'actions', formatter: 'actions',
formatoptions: {
keys: true,
editbutton: false,
delOptions: { url: '#Url.Action("DeleteCategory", "Categories")' }
}
}
],
pager: $('#CategoriesGrdPager'),
sortname: 'Code',
rowNum: 3,
rowList: [3, 6, 9],
width: '725',
height: '100%',
viewrecords: true,
beforeSelectRow: function (rowid, e) {
return true;
},
sortorder: 'desc'
}).navGrid('#CategoriesGrdPager', { edit: false, add: false, del: false, search: false, refresh: true });
You could add custom icons to the actions column of each line on gridComplete. See example below.
$('#CategoriesGrdList').jqGrid({
...
sortorder: 'desc',
gridComplete: function () {
var ids = $("#CategoriesGrdList").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var editIcon = "<div style='float: left;' class='ui-pg-div' onclick='myEditRow(\"" + id + "\");'><a class='ui-icon ui-icon-pencil'></a></div>";
var deleteIcon = "<div style='float: left;' class='ui-pg-div' onclick='myDeleteRow(\"" + id + "\");'><a class='ui-icon ui-icon-trash'></a></div>";
$("#gridDocs").jqGrid('setRowData', ids[i], { actions: editIcon + deleteIcon });
}
}
}).navGrid('#CategoriesGrdPager', { edit: false, add: false, del: false, search: false, refresh: true });
function myEditRow(rowId) {
var rowData = $("#CategoriesGrdList").jqGrid('getRowData', id);
//do something with the data i.e.
$('#nameEditInput').val(rowData.Code);
}
function myDeleteRow(rowId) {
//your delete code...
$("#" + id).hide();
}

Add DatePicker range in single column of jqgrid filter

I’ve been able to add a datepicker into the filter toolbar of a jqgrid with the code below. However, I’m wondering if there’s a way to squeeze two datepickers into this single DateCreated column, so as to specify the range (From, To). Any ideas?
function loadGrid() {
$(tableID).jqGrid({
…
colModel: [
…
{ name: 'DateCreated', index: 'DateCreated', width: 125, searchoptions:{dataInit:datePick, att:{title:'Select Date'}} },
…
})
…
}
datePick = function(elem) {
$(elem).datepicker();
}
If you are open to adding in a plugin, I found the range picker from filament group to be very easy to work with. In under an hour, I had the 3 files downloaded and installed into my project, and the range picker working.
link:filament group daterangepicker
Being that I'm using jquery 1.8 in my project, I ended up getting an updated version from
link:Github filament group daterangepicker jquery 1.8
daterangepicker is also able to take all of the options that datepicker supports, so you shouldn't have much trouble converting. Let me know if you have questions and I'll see if I can help.
For reference, the plugin is dual licensed with MIT and GPL. This is the same license structure as jqgrid, so I assume if you are able to use jqgrid, than this plugin should not be a problem.
UPDATE: Adding Code Example
The important part of this code is in the colModel for date. You simply specify a dataInit function for the search options, then add the daterangepicker. Be careful on the capitalization. That got me more than once. The beforeSelectRow is simply some modification I did in order to make my checkboxes along the side behave as a radio button. It is not needed for daterangepicker to work.
$("#myGrid").jqGrid(
{
url:url,
datatype: "json",
colNames:['Version','Date'],
colModel:[
{name:'version', search:true, stype:'text'},
{name:'date', search:true,stype:"text",searchoptions:{dataInit:function(el){
$(el).daterangepicker({dateFormat:'yy/mm/dd'});
}
}}
],
toolbarfilter: true,
sortname: 'version',
sortorder: "desc",
pager: jQuery('#myPager'),
viewrecords: true,
gridview: true,
multiselect: true,
beforeSelectRow: function(rowId)
{
var selectedIds = jQuery('#myGrid').jqGrid().getGridParam("selarrrow");
jQuery("#myGrid").jqGrid().resetSelection();
if(selectedIds)
{
var id = selectedIds[0]
if(id != rowId)
{
jQuery("#myGrid").jqGrid().setSelection(rowId, false);
}
}
else
{
jQuery("#myGrid").jqGrid().setSelection(rowId, false);
}
}
});
I had to do the very same thing, and Joseph's answer above got me 90% of the way there. So, most of the credit is due to him. I had to modify some stuff to get it to work because the filament date range picker allows for single dates (the today option, the specific date option, etc). I also had to add some code to trigger the search after you selected your date. Here's my update...the meat of what I needed to add was in the beginRequest function:
$(document).ready(function() {
var grid = jQuery('#list').jqGrid({
url: '/myajaxurl',
datatype: 'json',
mtype: 'GET',
colNames: ['Reference #', 'CreatedOn', 'Product', 'Model Number', 'Quantity', 'Transaction Type', 'Created By'],
colModel: [
{ name: 'InventoryTransactionLogId', index: 'InventoryTransactionLogId', align: 'center', sortable: true, search: false },
{
name: 'CreatedOn',
search: true,
stype: 'text',
align: 'center',
formatter: 'date',
formatoptions: { newformat: 'm-d-y H:i' },
sortable: true,
searchoptions: {
dataInit: function(el) {
$(el).daterangepicker({ dateFormat: 'yy/mm/dd', onChange: datePick });
}
}
},
{ name: 'ProductName', index: 'ProductName', align: 'center', sortable: true, search: false },
{ name: 'ModelNo', index: 'ModelNo', align: 'center', sortable: true, search: true },
{ name: 'Quantity', index: 'Quantity', align: 'center', sortable: true, search: false },
{ name: 'Description', index: 'Description', align: 'center', sortable: true, search: false },
{ name: 'UserName', index: 'UserName', align: 'center', sortable: true, search: false }
],
loadtext: "Retrieving Inventory Transaction Log...",
rowNum: 50,
rowList: [25, 50, 100],
sortname: 'InventoryTransactionLogId',
sortorder: 'asc',
pager: '#pager',
ignoreCase: true,
viewrecords: true,
height: 450,
autowidth: true,
scrollOffset: 45,
caption: 'Inventory Transaction Log',
emptyrecords: "No records",
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
cell: 'cell',
id: 'InventoryTransactionLogId',
userdata: 'userdata'
},
beforeRequest: function () {
var theGrid = jQuery("#list");
var postData = theGrid.jqGrid('getGridParam', 'postData');
if (postData != undefined && postData.filters != undefined) {
postData.filters = jQuery.jgrid.parse(postData.filters);
//Remove if current field exists
postData.filters.rules = jQuery.grep(postData.filters.rules, function(value) {
if (value.field != 'CreatedOn')
return value;
});
// Parse the range picker field into start/end date
var dateRangeString = $('#gs_CreatedOn').val();
if (dateRangeString.length > 0) {
var dateRange = dateRangeString.split(' - ');
if (dateRange.length == 1) {
startDate = dateRange[0] + ' 00:00:00';
endDate = dateRange[0] + ' 23:59:59.999';
} else {
startDate = dateRange[0] + ' 00:00:00';
endDate = dateRange[1] + ' 23:59:59.999';
}
var startDateFilter = { "field": "CreatedOn", "op": "ge", "data": startDate };
var endDateFilter = { "field": "CreatedOn", "op": "le", "data": endDate };
// Add new filters
postData.filters.rules.push(startDateFilter);
postData.filters.rules.push(endDateFilter);
}
} else {
jQuery.extend(postData, {
});
}
if (postData != undefined && postData.filters != undefined) {
postData.filters = JSON.stringify(postData.filters);
postData._search = true;
}
return [true, ''];
}
});
$('.date').datepicker();
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "bw" });
grid.jqGrid('navGrid', '#pager', { del: false, add: false, edit: false, search: false });
});
datePick = function() {
var grid = $("#list");
$("#list")[0].triggerToolbar();
$("#list").trigger("reloadGrid", [{ page: 1 }]);
}

jqGrid parameters. Can't be passed

I call web-service to fill jqGrid and wants to pass parameters to it
I use the following code (client side):
jQuery('#EmployeeTable').jqGrid({
datatype: function () {
var params = new Object();
params.page = 10;
params.Filter = true;
params.DateStart = null;
params.DateEnd = null;
params.TagID = null;
params.CategoryID = 3;
params.StatusID = 1;
params.IsDescription = true;
$.ajax({
url: '/Admin/IdeasJSON',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
dataType: "json",
success: function (data, st) {
if (st == "success") {
var grid = $("#EmployeeTable")[0];
grid.addJSONData(data);
}
},
error: function () {
alert("Error with AJAX callback");
}
});
},
also, there is propotype of web-method (MVC):
public JsonResult IdeasJSON(int? page, bool? Filter, DateTime? DateStart, DateTime? DateEnd, int? TagID, int? CategoryID, int? StatusID, bool? IsDescription)
Why all these parameters are null?
[ADDED 04/11]
jQuery(document).ready(function () {
var StatusID = null, Filter = null, page = null, DateStart = null, DateEnd = null, TagID = null, CategoryID = null, IsDescription = null;
if (jQuery.url.param('StatusID') != null) {
StatusID = jQuery.url.param('StatusID');
}
if (jQuery.url.param('Filter') != null) {
Filter = jQuery.url.param('Filter');
}
if (jQuery.url.param('page') != null) {
page = jQuery.url.param('page');
}
if (jQuery.url.param('DateStart') != null) {
DateStart = jQuery.url.param('DateStart');
}
if (jQuery.url.param('DateEnd') != null) {
DateEnd = jQuery.url.param('DateEnd');
}
if (jQuery.url.param('TagID') != null) {
TagID = jQuery.url.param('TagID');
}
if (jQuery.url.param('CategoryID') != null) {
CategoryID = jQuery.url.param('CategoryID');
}
if (jQuery.url.param('IsDescription') != null) {
IsDescription = jQuery.url.param('IsDescription');
}
jQuery('#EmployeeTable').jqGrid({
url: '/Admin/IdeasJSON',
datatype: 'json',
postData: { page: page, Filter: Filter, DateStart: DateStart, DateEnd: DateEnd, TagID: TagID, StatusID: StatusID, CategoryID: CategoryID, IsDescription: IsDescription },
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Logged By', 'Logging Agency (ID)', 'Title', 'Status', 'Points', 'Categories', 'Created Date', 'Description', 'Jira ID#', 'Portal Name', '', '', '', '', '', '', ''],
colModel: [
{ name: 'LoggedBy', width: 100 },
{ name: 'LoggingAgencyID', width: 85 },
{ name: 'Title', width: 100 },
{ name: 'Status', width: 100 },
{ name: 'Points', width: 40, align: 'center' },
{ name: 'Categories', width: 100 },
{ name: 'CreatedDate', width: 80, formatter: ndateFormatter },
{ name: 'Description', width: 300 },
{ name: 'JiraID', width: 55 },
{ name: 'PortalName', width: 100 },
{ name: 'IdeaID', width: 25, formatter: ActionDescriptionFormatter },
{ name: 'IdeaID', width: 25, formatter: ActionEditFormatter },
{ name: 'IdeaID', width: 25, formatter: ActionDeleteFormatter },
{ name: 'IdeaGridCommentsAndSubideas', width: 25, formatter: ActionIdeaGridCommentsAndSubideas },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridCountVotes },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridLinkIdeas },
{ name: 'IdeaGridCountVotes', width: 25, formatter: ActionIdeaGridIdeaType },
],
pager: '#EmployeeTablePager',
width: 1000,
viewrecords: true,
caption: 'Idea List',
excel: true
}).jqGrid('navGrid', '#EmployeeTablePager', {
add: false,
edit: false,
del: false,
search: false,
refresh: false
}).jqGrid('navButtonAdd', '#EmployeeTablePager', {
caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: ReturnExcel,
position: "last"
}).jqGrid('navButtonAdd', '#EmployeeTablePager', {
caption: " Export to CSV ",
buttonicon: "ui-icon-bookmark",
onClickButton: ReturnCSV,
position: "last"
});
});
You should not use datatype as the function to use the JSON data. Probably you used template of very old examples.
For example in the "UPDATED" part of the answer you could find full demo project which demonstrate how to use jqGrid in ASP.MVC 2.0 inclusive paging, sorting and filtering/advanced searching.
If you want post some additional parameters to the server as a part of jqGrid request you should use postData parameters in the form postData: {CategoryID: 3, StatusID: 1, IsDescription:true, Filter: true}

Resources