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.
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 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>
i want to send data from kendo grid to sql database, here is my javascript view model code:
document.onreadystatechange = function () {
var viewModel = kendo.observable({
products: new kendo.data.DataSource({
schema: {
//data:"Data",
total: "Count",
model: {
Id: "Id",
fields: {
Id: { editable: true, type: "int" },
ShortName: { editable:true, type: "string" },
FullName: { editable: true, type: "string" },
ContactPerson: { editable: true, type: "string" },
CurrentCurrencyCode: { editable: true, type: "int" },
Adress1: { editable: true, type: "string" },
CompanyState: { editable: true, type: "string" },
CompanyCity: { editable: true, type: "string" },
CompanyCountry: { editable: true, type: "string" },
ZipPostCode: { editable: true, type: "string" },
TelArea: { editable: true, type: "string" }
}
}
},
batch: true,
transport: {
read: {
url: "/api/Companies/GetAllCompanies",
dataType: "json"
},
create:{
url: "/api/Companies/SaveDefCompny", // here is a correct api url, which i want to call
dataType: "json"
},
destroy: {
url: "/api/Companies/Delete",
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data) {
return kendo.stringify(data) ;
}
}
}
})
});
kendo.bind(document.getElementById("example"), viewModel);
}
Here is my controller code to post data to database but its is not calling by clicking create or update button what the problem with my grid or controller call?
[HttpPost]
public void SaveDefCompny(IEnumerable<DefCompanyDTO> DfCmpny1)
{
var result = new List<DefCompany>();
using (var data = new RPDBEntities())
{
foreach (var productViewModel in DfCmpny1)
{
var product = new DefCompany
{
Id = productViewModel.Id,
CurrentCurrencyCode = productViewModel.CurrentCurrencyCode,
ShortName= productViewModel.ShortName,
FullName= productViewModel.FullName,
ContactPerson= productViewModel.ContactPerson,
Address1= productViewModel.Address1,
CompanyCity= productViewModel.CompanyCity,
CompanyState= productViewModel.CompanyState,
CompanyCountry= productViewModel.CompanyCountry,
ZipPostCode= productViewModel.ZipPostCode,
TelArea= productViewModel.TelArea
};
result.Add(product);
data.DefCompanies.Add(product);
};
data.SaveChanges();
}
}
the url is correct but it doesnot called even while debugging cursor not goes to url but grid reads all values and display in it
As you are going to post data type: "POST" is missing in create method.
And also check posting data.models instead of data
net mvc4 c# razor project i want to implement dotnet highcharts.For that i have created a jsonresult function to get the data from datatable and a cshtml file to render the file.
Here my issue is that
1. i dont how to pass the data from json to view
2. how to display the result for x axis and series in highcharts.
Am beginner in asp.net mvc 4 and Highcharts..
cshtml
enter code here
<script type="text/javascript">
$(function () {
debugger;
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Audience Live Data'
},
subtitle: {
text: 'Mainadv'
},
xAxis: {
categories: [mySeries]
},
yAxis: {
min: 0,
title: {
text: 'Count'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Home',
data: [{ data: data }]
}, {
name: 'Category',
data: [{ data: data }]
}, {
name: 'Product',
data: [{ data: data }]
}, {
name: 'Basket',
data: [{ data: data }]
},{
name: 'Checkout',
data: [{ data: data }]
}]
});
});
</script>
Script file
<script type="text/javascript">
// the button action
debugger;
var url = "/AudienceLive/GetAudLiveChartData/";
$.ajax({
url: url,
cache: false,
Type: 'POST',
success: function (myData) {
var mySeries = [];
for (var i =0; i < myData.length; i++) {
mySeries.push([myData[i]]);
}
var chart = $('#container').highcharts();
chart.series[0].setData(mySeries);
// chart.series[0].pointStart=;
}, error: function (response) {
alert("error : " + response);
}
});
</script>
JsonResult Function
public JsonResult GetAudLiveChartData()
{
AudienceLiveRepo objlive=new AudienceLiveRepo ();
List<string> test=new List<string>();
DataTable dt = objlive.GetTable();
if(dt!=null)
{
if(dt.Rows.Count>0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
test.Add(Convert.ToString(dt.Rows[i][0]));
test.Add(Convert.ToString(dt.Rows[i][1]));
test.Add(Convert.ToString(dt.Rows[i][2]));
test.Add(Convert.ToString(dt.Rows[i][3]));
test.Add(Convert.ToString(dt.Rows[i][4]));
test.Add(Convert.ToString(dt.Rows[i][5]));
}
}
}
objlive = null;
return Json(test, JsonRequestBehavior.AllowGet);
}
View cshtml
$(document).ready(function () {
$.ajax({
url: "/home/ChartData",
type: 'POST',
dataType: 'json'
}).success(function (dataChart) {
var Xaxis = [];//skapa tre olika array
var dataseries = [];
for (var i = 0; i < dataChart.length; i++) {
var items = dataChart[i];
var XcategoreisItem = items.id;
var seriesData = items;
Xaxis.push(XcategoreisItem);
dataseries.push(seriesData);
console.log(dataseries);
}
getchart(Xaxis, dataseries);
}).error(function (er, xhr, e) {
console.log("Error: ", er, xhr, e);
})
});
function getchart(Xaxis, dataseries) {
$('#container').highcharts({
chart: {
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift'
},
title: {
text: 'Zooming and panning'
},
subtitle: {
text: 'Click and drag to zoom in. Hold down shift key to pan.'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{y}%',
}
}
},
xAxis: {
categories: Xaxis
},
yAxis: {
title: {
text: 'Y axis text'
},
series: [{
name: 'Id',
data: dataseries
}]
});
};
HomeController
public ActionResult ChartData()
{
TbChart db = new TbChart();
var TbChartData = db.getYaxis();
return this.Json(TbChartData, JsonRequestBehavior.AllowGet);
}