I have a kendo grid that is edited inline. One of the fields should be edited selecting an element from a list, but the list must have a hierarchical structure (would be nice be able of filter that list). I was thinking in use a kendo treeview as editor for that field but I haven't found any way to accomplish this. I tried make a custom editor template (using columns.Bound(s => s.FieldId).EditorTemplateName("_TreeEditorTemplate")) that render the treeview, but the treeview is not an input and is not selectable. I also thinked in make an editor that use a kendo dropdownlist with the tree inside but this is no currently supported by kendo. Any ideas???
Have you looked at the sample on the Kendo site: https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Editing/use-treeview-as-grid-editor
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "//demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1 } },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
},
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
edit: function (e) {
//checking if a cell from the Test column is opened for editing
var dummyInput = e.container.find("input[name='test']");
if (dummyInput.length > 0) {
var treeView = $(e.container).find(".treeViewEditor").data("kendoTreeView");
var originalItem = treeView.findByText(dummyInput.val());
if (originalItem != null) {
// Select the item based on the field value
treeView.select(originalItem);
}
}
},
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{
field: "test", title: "Test", width: 120,
editor: function (container, options) {
var input = $("<input class='tveInput'/>");
input.attr("name", options.field);
var tvDiv = $("<div class='treeViewEditor'></div>");
$(tvDiv).kendoTreeView({
animation: false,
dataSource: [
{
text: "foo1"
},
{
text: "foo2",
items: [
{ text: "bar" },
{ text: "bar1" },
{ text: "bar2" }
]
}
]
});
var treeView = $(tvDiv).data("kendoTreeView");
$(tvDiv).find(".k-in").mousedown(function (e) {
var clickedNode = $(e.toElement).closest("[role=treeitem]");
var dataItem = treeView.dataItem(clickedNode);
var dummyInput = clickedNode.closest("[role=gridcell]").find("input[name='test']");
dummyInput.val(dataItem.text);
dummyInput.trigger("change");
});
tvDiv.appendTo(container);
input.appendTo(container);
}
},
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120 },
{ command: "destroy", title: " ", width: 150 }],
editable: true
});
});
</script>
</div>
<style>
.tveInput {
display: none;
}
</style>
Related
am trying to bind data from Database to Echart, My query returns the following value:
Transaction Iteration1
Init----------------- 0.02
Login ------------- 2.29
App --------------- 6.08
Up --------------- 4.88
Select ----------- 3.46
Log ---------------- 0.26
The Iteration column increases for example if i select two iteration, i will get 3 column that is Transaction---- Iteration1 ----- Iteration2
My query is running fine.
My json format:
data[ { Transaction:init, iteration:0.02 }, {
Transaction:Login,iteration1:2.29 }, { Transaction:App,
iteration1:6.08 }, { Transaction:Up, iteration1:4.88 }, {
Transaction:select, iteration1:3.46 }, {Transaction:Log,
iteration1:0.26 } ]
var myChart = echarts.init(document.getElementById('main'));
var params = {
runIds: '1'
};
$.ajax({
url: transactionUrl,
type: 'POST',
dataType: 'JSON',
contentType: 'application/json;',
data: JSON.stringify(params),
beforeSend: function () {
},
success: function (d) {
var seriesHeader = [];
if (seriesHeader.length === 0) {
seriesHeader.push('Transaction');
for (var key in d[0]) {
if (d[0].hasOwnProperty(key)) {
if (key !== 'Transaction') {
seriesHeader.push(key);
}
}
}
}
$.each(d, function (i, item) {
var count = 0;
while (count < seriesHeader.length) {
count += 1;
}
});
var option = {
title: {
//text: 'ECharts entry example'
},
tooltip: {},
legend: {
data: seriesHeader
},
xAxis: {
data: ???
},
yAxis: {},
series: [{
name: seriesHeader[1],
type: 'bar',
data: ??
}
]
};
// use configuration item and data specified to show chart
myChart.setOption(option);
},
error: function () {
}
});
Am a bit confuse how to pass the data to the Echart. Am help will be most welcome.
Please check this demo, assuming there are 2 Iteration.
Is this you want?
let echartsObj = echarts.init(document.querySelector('#canvas'));
let d = [{
Transaction: 'init',
iteration1: 0.02,
iteration2: 2.02,
}, {
Transaction: 'Login',
iteration1: 2.29,
iteration2: 0.52,
}, {
Transaction: 'App',
iteration1: 6.08,
iteration2: 3.53,
}, {
Transaction: 'Up',
iteration1: 4.88,
iteration2: 5.32,
}, {
Transaction: 'select',
iteration1: 3.46,
iteration2: 2.11,
}, {
Transaction: 'Log',
iteration1: 0.26,
iteration2: 1.02,
}]
let seriesHeader = d.map(item => item.Transaction)
let datas = [];
Object.keys(d[0]).forEach(key => {
if (key !== 'Transaction') {
datas.push({
name: key,
type: 'bar',
data: d.map(item => item[key])
})
}
})
option = {
xAxis: {
type: 'category',
data: seriesHeader
},
yAxis: {
type: 'value'
},
legend: {
data: datas.map(item => item.name)
},
series: datas
};
echartsObj.setOption(option)
<html>
<header>
<script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.min.js"></script>
</header>
<body>
<div id="canvas" style="width: 100%; height: 200px">
</div>
</body>
</html>
I have Kendo Grid in my view. I have specified read , edit and delete each as of type HTTPPOST. But when I try to edit or delete i get an error that : "A public action method 'UpdateDetails' was not found on controller 'Nop.Plugin.Misc.CategoryWiseShipping.Controllers.ShippingChargeController'." for update Action and similarly one other for delete option.
Interesting thing is that it works fine on my local machine but throws error when published to server
I have searched extensivelly on google but couldn't find the reason as to why it is happening.
This is the controller actionMethod
[HttpPost]
public ActionResult UpdateDetails(ShippingChargeModel shippingChargeModel)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
return AccessDeniedView();
if (shippingChargeModel.SchoolEmail == null)
{
ErrorNotification(" Email can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleStartDate == null)
{
ErrorNotification(" Sale start date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate == null)
{
ErrorNotification(" Sale end date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate < shippingChargeModel.SaleStartDate)
{
ErrorNotification(" Sale start date should be less than sale end date!!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
var modelFromDb = _catShippingService.GetRecord(shippingChargeModel.Id);
modelFromDb.SaleEndDate = shippingChargeModel.SaleEndDate.Value.AddMinutes(330);
modelFromDb.SaleStartDate = shippingChargeModel.SaleStartDate.Value.AddMinutes(330);
modelFromDb.SchoolEmail = shippingChargeModel.SchoolEmail;
modelFromDb.ShippingCharge = shippingChargeModel.ShippingCharge;
modelFromDb.ModifyDate = DateTime.Now;
_catShippingService.Update(modelFromDb);
return new NullJsonResult();
}
This is my Kendo Grid :
function loadKendo() {
var dataNew = {};
$("#shippingCharge-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
},
update: {
url: "#Html.Raw(Url.Action("UpdateDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
//data: addAntiForgeryToken
},
destroy: {
url: "#Html.Raw(Url.Action("DeleteDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
}
,
parameterMap: function (data, operation) {
if (operation === "update") {
dataNew.Id = data.Id;
dataNew.CategoryId = data.CategoryId;
dataNew.ShippingCharge = data.ShippingCharge;
dataNew.SaleStartDate = stringToTimestamp(data.SaleStartDate.toUTCString());
dataNew.SaleEndDate = stringToTimestamp(data.SaleEndDate.toUTCString());
dataNew.SchoolEmail = data.SchoolEmail;
return { ShippingChargeModel: dataNew };
}
return data;
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
//ProductId: { editable: false, type: "number" },
CategoryId: { editable: false, type: "string" },
CategoryName: { editable: false, type: "string" },
ShippingCharge: { editable: true, type: "number" },
SaleStartDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SaleEndDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SchoolEmail: { editable:true, type: "string" }
}
}
},
requestEnd: function (e) {
if (e.type == "update") {
this.read();
}
if (e.type == "cancel") {
this.cancelChanges();
}
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info: false,
pageSizes: [#(gridPageSizes)]
},
editable: {
confirmation: "#T("Admin.Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "CategoryName",
title: "CategoryName",
width: 300
},
{
field: "ShippingCharge",
title: "Shipping Charge",
width: 100,
encoded: false
}
,
{
field: "SchoolEmail",
title: "Email",
width: 200,
encoded: false
}
,
{
field: "SaleStartDate",
title: "Sale Start Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleStartDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
},
{
field: "SaleEndDate",
title: "Sale End Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleEndDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
}, {
command: [
{
name: "edit",
text: {
edit: "#T("Admin.Common.Edit")",
update: "#T("Admin.Common.Update")",
cancel: "#T("Admin.Common.Cancel")"
}
}
, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
}
Please help me out. Any sort of insight will do ...
I want to fetch data from server into a datatable in asp.net mvc5. I have my own datatable template which I want to customize but I couldn't fetch the data. The ajax call plus datatable itself is like below:
var DatatableRemoteAjaxDemo = function() {
//== Private functions
// basic demo
var demo = function() {
var datatable = $('.m_datatable').mDatatable({
// datasource definition
data: {
type: 'remote',
source: {
read: {
// sample GET method
method: 'GET',
url: '/ActionLinks/getActionLinks',
map: function(raw) {
// sample data mapping
var dataSet = raw;
if (typeof raw.data !== 'undefined') {
dataSet = raw.data;
}
return dataSet;
},
},
},
pageSize: 10,
saveState: {
cookie: true,
webstorage: true,
},
serverPaging: true,
serverFiltering: true,
serverSorting: true,
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false, // enable/disable datatable scroll both horizontal and vertical when needed.
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
toolbar: {
// toolbar items
items: {
// pagination
pagination: {
// page size select
pageSizeSelect: [10, 20, 30, 50, 100],
},
},
},
search: {
input: $('#generalSearch'),
},
// columns definition
columns: [
{
field: 'ActionLinkId',
title: '#',
sortable: false, // disable sort for this column
width: 40,
selector: false,
textAlign: 'center',
}, {
field: 'ActionText',
title: 'Quiz Title',
// sortable: 'asc', // default sort
filterable: false, // disable or enable filtering
width: 150,
}, {
field: 'ActionDescription',
title: 'Quiz Description',
width: 150,
}, {
field: 'Category',
title: 'Category',
}, {
field: 'SmallImageURL',
title: 'Small Image URL',
width: 100,
}, {
field: 'LargeImageURL',
title: 'Large IMG URL',
width: 100,
},{
field: 'DateCreated',
title: 'CreationDate',
sortable: 'asc',
type: 'date',
format: 'MM/DD/YYYY',
}],
});
var query = datatable.getDataSourceQuery();
$('#m_form_status').on('change', function() {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Status = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Status !== 'undefined' ? query.Status : '');
$('#m_form_type').on('change', function() {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Type = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Type !== 'undefined' ? query.Type : '');
$('#m_form_status, #m_form_type').selectpicker();
};
return {
// public functions
init: function() {
demo();
},
};
}();
jQuery(document).ready(function() {
DatatableRemoteAjaxDemo.init();
});
My JsonResult code to fetch data from database is like below:
public JsonResult getActionLinks()
{
var actionlinks = db.ActionLinks.OrderBy(i => i.ActionLinkId).ToList();
return Json(new { data = actionlinks }, JsonRequestBehavior.AllowGet);
}
I debugged it the call hits the URL but I can't fetch the data into my datatable. It says 304 error. Please help.
I am using MVC4 ASP.NET and trying to create a Kendo Grid where I can edit data inline. I am connecting to a local database imported into Visual Studio using the Entity Framework. I followed the sample example on Kendos web page from here: http://demos.telerik.com/kendo-ui/grid/editing-inline Here is my View
Edit
When I click on the Update button after modifying an existing record in the Grid, it is not firing up in my Controller UpdateAsset method. I have also added an alert method in the Views update method and have not received the dialog box.
File code:
#{
ViewBag.Title = "Manage Assets";
}
<h2>ManageAssets</h2>
<div id="grid"></div>
<div>
<form style="background-color:#E6E6FA">
Switch:<input type="number" id="switch_txt" /><br />
Port:<input type="text" id="port_txt" /><br />
Name:<input type="text" id="name_txt" /><br />
Connection:<input type="text" id="connection_txt" /><br />
Interface:<input type="text" id="ifc_txt" /><br />
</form>
</div>
<div>
#*<input type="text" id="switchTxt" />*# #*This is Justins original code (JOC) *#
<button onclick="onSave()">Save</button><br />
</div>
<script>
var selectedRow = {};
var crudServiceBaseUrl = "/Asset";
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/GetAssets",
dataType: "json",
contentType: "application/json"
},
update: {
url: crudServiceBaseUrl + "/UpdateAsset",
dataType: "json",
type: "POST",
contentType: "application/json"
},
destroy: {
url: crudServiceBaseUrl + "/Destroy",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 20,
autoSync: true,
schema: {
model: {
id: "Gid",
fields: {
Switch: { type: "number", editable: true, nullable: true, validation: { required: true, min: 1 } },
Port: { type: "string", editable: true, nullable: true },
Name: { type: "string" },
Connection: { type: "string" },
Interface: { type: "string" },
ConnectionUser: { type: "string" },
ConnectionDate: { type: "string" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
selectable: true,
change: function () {
selectedRow = {
mySwitch: this.dataItem(this.select()).Switch,
myPort: this.dataItem(this.select()).Port,
myName: this.dataItem(this.select()).Name,
myConnection: this.dataItem(this.select()).Connection,
myInterface: this.dataItem(this.select()).Interface
};
alert(selectedRow['mySwitch']);
},
columns: [
{ field: "Switch", title: "Switch", format: "{0:n}", width: "120px" },
{ field: "Port", title: "Port" },
{ field: "Name", title: "Name" },
{ field: "Connection", title: "Connection" },
{ field: "Interface", title: "Interface" },
//{ command: ["edit", "destroy"], title: " ", width: "250px" }],
{ command: [
{
name: "edit",
//click: function(e) {
// alert("you just clicked edit");
//}
},
{ name: "destroy"}
]}],
editable: "inline"
});
});
// when the Save button is pressed this function is called
// the function creates the values for the table columns
function onSave() {
var myJSONObject = {
//switchTxt is coming from the text field div
asset_sw: $("#switch_txt").val(),
asset_port: $("#port_txt").val(),
asset_name: $("#name_txt").val(),
asset_conn: $("#connection_txt").val(),
asset_ifc: $("#ifc_txt").val()
};
//alert(myJSONObject);
$.ajax({
url: crudServiceBaseUrl + "/CreateAsset",
dataType: "json",
type: "POST",
data: myJSONObject, // here we pass the json object that contains all of our data
success: function (result) {
if (result.success == true)
{
alert(result.success);
alert('success');
$('#grid').data('kendoGrid').dataSource.read();
$('#grid').data('kendoGrid').refresh();
}
else {
alert(result.success);
alert('fail success');
}
},
error: function (result) {
alert(result);
alert('fail')
}
});
}
</script>
Is there a way to set the models value on a page load. Because i need it to populate a schema with model values. and i tried a document.ready ajax call to get the model but it tells me that the model has no value before the ajax call even happens.
here is the code and you can see how im trying to populate the schema but it wont hit the functions
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")"> </script>
<script src="#Url.Content("~/Scripts/kendo/kendo.all.min.js")"></script>
<script>
$(document).ready(function () {
$.ajax({
url: '/Team/Calendar/PopulateCalendar/',
type: "POST",
data: $(this).serialize(),
});
});
$(function () {
$("#scheduler").kendoScheduler({
date: new Date("2013/6/13"),
startTime: new Date("2013/6/13 07:00 AM"),
height: 600,
views: [
"day",
{ type: "week", selected: true },
"month",
"agenda"
],
timezone: "Etc/UTC",
dataSource: {
batch: true,
transport: {
read: {
url: "/Team/Calendar/PopulateCalendar/",
dataType: "json"
},
update: {
url: "http://demos.kendoui.com/service/tasks/update",
dataType: "jsonp"
},
create: {
url: "http://demos.kendoui.com/service/tasks/create",
dataType: "jsonp"
},
destroy: {
url: "http://demos.kendoui.com/service/tasks/destroy",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "taskId",
fields: {
taskId: { from: "#Model.CalendarItems.Select(calendar=> calendar.TaskId)", type: "number" },
title: { from: "#Model.CalendarItems.Select(calendar=> calendar.Title)", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "#Model.CalendarItems.Select(calendar => calendar.Start)" },
end: { type: "date", from: "#Model.CalendarItems.Select(calendar => calendar.End)" },
startTimezone: { from: "#Model.CalendarItems.Select(calendar => calendar.StartTimezone)" },
endTimezone: { from: "#Model.CalendarItems.Select(calendar => calendar.EndTimezone)" },
description: { from: "#Model.CalendarItems.Select(calendar => calendar.Description)" },
recurrenceId: { from: "#Model.CalendarItems.Select(calendar => calendar.RecurrenceId)" },
recurrenceRule: { from: "#Model.CalendarItems.Select(calendar => calendar.RecurrenceRule)" },
recurrenceException: { from: "#Model.CalendarItems.Select(calendar => calendar.RecurrenceException)" },
ownerId: { from: "OwnerID", defaultValue: 1 },
isAllDay: { type: "boolean", from: "#Model.CalendarItems.Select(calendar => calendar.IsAllDay)" }
}
}
},
filter: {
logic: "or",
filters: [
{ field: "ownerId", operator: "eq", value: 1 },
{ field: "ownerId", operator: "eq", value: 2 }
]
}
},
resources: [
{
field: "ownerId",
title: "Owner",
dataSource: [
{ text: "Alex", value: 1, color: "#f8a398" },
{ text: "Bob", value: 2, color: "#51a0ed" },
{ text: "Charlie", value: 3, color: "#56ca85" }
]
}
]
});
I think you are using ASPNET MVC with Razor, you should be able to set your model via Scriplet into the javascript.