How to bind model list variable to highchart - asp.net-mvc-4

#model List<Monitoring>
<script>
function drawAWSInstancesMonitoring() {
var seriesData = [];
#foreach (var item in Model)
{
seriesData.push([Date.parse(new Date(parseInt((item.SampleDateTime).substr(6)))), item.PercentUsed]);
}
$('#chart_Monitoring').highcharts('StockChart', {
rangeSelector: {
selected: 1,
inputEnabled: false
},
title: { text: 'Utilization' },
yAxis: { type: 'double', min: 0 },
xAxis: {
type: 'datetime',
labels: {
formatter: function () { return Highcharts.dateFormat('%a %d %b %H:%M', this.value); },
dateTimeLabelFormats: {
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
}
}
},
series: [{
name: 'Usage',
data: seriesData,
tooltip: {
valueDecimals: 2
}
}]
});
}
</script>
HTML
<div id="chart_Monitoring" class="col-sm-12" style="height: 350px;"></div>`
how bind directly model to highchart ?

you can not use server variable in js. so you need to parse your model in json like
var model = '#Html.Raw(Json.Encode(Model))';
var data = JSON.parse(model);
var seriesData = [];
for (i = 0; i < data.length; i++) {
seriesData.push([Date.parse(new Date(parseInt((data[i].SampleDateTime).substr(6)))), data[i].PercentUsed]);
}

Related

TreeGrid extension for DataTables - how to get a checkbox added after name?

I found a TreeGrid extension for DataTables:
https://homfen.github.io/dataTables.treeGrid.js/
but instead of the name I would like to add a column between name and position and place a checkbox here.
However when I do this e.g.:
var columns = [
{
title: '',
target: 0,
className: 'treegrid-control',
data: function (item) {
if (item.children) {
return '<span>+<\/span>';
}
return '';
}
},
{
title: 'Name',
target: 1,
data: function (item) {
return item.name;
}
},
{
defaultContent: '',
target: 2,
className: 'select-checkbox',
function(item) {
return item;
}
},
{
title: 'Position',
target: 3,
data: function (item) {
return item.position;
}
},
{
title: 'Office',
target: 4,
data: function (item) {
return item.office;
}
},
{
title: 'Extn.',
target: 5,
data: function (item) {
return item.extn;
}
},
{
title: 'Start date',
target: 6,
data: function (item) {
return item.start;
}
},
{
title: 'Salary',
target:7,
data: function (item) {
return item.salary;
}
}
];
I get an extra column but when checking the parent does not select all underlying children rows.
Anyone have an idea how to establish this?
Edit: updated the columns definition.
When I add a button to read the selected values e.g.:
dom: 'Bfrtip',
select:true,
buttons: [
{
text: 'Alert selected',
action: function(e, dt, node, config) {
var data = table.rows({
selected: true
}).data().toArray();
var i;
var text = new Array();
for (i = 0; i < data.length; i++) {
text.push(data[i].name);
}
alert("you selected: " + text.join(",") );
console.log("text---" + text.join(","));
}
}
]
the table starts to behave oddly for example: the selection of underlying children stops.

Trying to refresh label when click on it. Cannot read property '_meta' of undefined"

I'm trying that the percentages in a pie-chart refresh when clicking in a legend to hide data.
So far, I can display the chart with percentages, but they don't change if I hide one of the legends.
This is the chart: initial chart
This is how looks after the click: after click
We expect that instead 55.6%, it shows 100%.
This is my code so far:
<script>
import {Pie} from "vue-chartjs";
import ChartJsPluginDataLabels from 'chartjs-plugin-datalabels';
export default {
extends: Pie,
ChartJsPluginDataLabels,
props: {
data: Array,
bg: Array,
labels: Array
},
data() {
return {
}
},
computed: {
chartData() {
return this.data
},
bgData() {
return this.bg
},
total() {
return this.data.reduce((a, b) => a + (b || 0), 0)
}
},
methods: {
renderPieChart() {
this.renderChart({
labels: this.labels,
datasets: [
{
label: "Data One",
backgroundColor: this.bgData,
data: this.chartData,
hoverBackgroundColor: "#f78733"
}
]
}, {
responsive: true,
plugins: {
datalabels: {
formatter: (value) => {
let sum = this
.$refs.canvas.getContext('2d').dataset._meta[1].total; //use this.total to fix percentages
let percentage = (value * 100 / sum).toFixed(1) + "%";
return percentage;
},
color: '#fff'
}
}
})
console.log()
},
updateSelected(point, event) {
const item = event[0]
this.selected = {
index: item._index,
value: this
.chartData
.datasets[0]
.data[item._index]
}
}
},
watch: {
bg: function () {
this.renderPieChart();
},
data: function () {
this.renderPieChart();
}
},
}
</script>
In order to obtain the expected result, you should define plugins.datalabels.formatter as follows:
formatter: (value, context) => {
return (value * 100 / context.dataset._meta[0].total).toFixed(1) + "%";
}
new Chart(document.getElementById("myChart"), {
type: "pie",
data: {
labels: ['Savings', 'House'],
datasets: [{
label: "Data One",
backgroundColor: ['#4e9258', '#64e986'],
data: [9, 7],
hoverBackgroundColor: "#f78733"
}]
},
options: {
plugins: {
datalabels: {
formatter: (value, context) => {
return (value * 100 / context.dataset._meta[0].total).toFixed(1) + "%";
},
color: '#fff'
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<canvas id="myChart" height="100"></canvas>

How can i use view charts in my js file using vuejs?

I have one project that contain index.html,script.js,style.js I need to use vue-echart for a single page how can i use?
<script src="https://cdn.jsdelivr.net/npm/echarts#4.1.0/dist/echarts.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-echarts#4.0.2"></script>
<script src="vue.js"></script>
<script type="module" src="newScript.js"></script>
index.html
<div class="echarts">
<IEcharts
:option="bar"
:loading="loading"
#ready="onReady"
#click="onClick"
/>
<button #click="doRandom">Random</button>
</div>
newScript.js
//import IEcharts from 'vue-echarts-v3/src/full.js';
export default {
name: 'view',
components: {
IEcharts
},
props: {},
data: () => ({
loading: true,
bar: {
title: {
text: 'ECharts Hello World'
},
tooltip: {},
xAxis: {
data: ['Shirt', 'Sweater', 'Chiffon Shirt', 'Pants', 'High Heels', 'Socks']
},
yAxis: {},
series: [{
name: 'Sales',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
}
}),
methods: {
doRandom() {
const that = this;
let data = [];
for (let i = 0, min = 5, max = 99; i < 6; i++) {
data.push(Math.floor(Math.random() * (max + 1 - min) + min));
}
that.loading = !that.loading;
that.bar.series[0].data = data;
},
onReady(instance, ECharts) {
console.log(instance, ECharts);
},
onClick(event, instance, ECharts) {
console.log(arguments);
}
}
};
When i use the mentioned way i am getting an error
Uncaught
ReferenceError: IEcharts is not defined.
//import IEcharts from 'vue-echarts-v3/src/full.js';
This line above is comment because there was error full.js is not found.
You need use global variable to register component. (Ref)
So, change IEcharts to "v-chart": VueECharts
For example:
// https://github.com/ecomfe/vue-echarts#using-the-component
var app = new Vue({
el: "#app",
components: {
"v-chart": VueECharts
},
data() {
let data = []
for (let i = 0; i <= 360; i++) {
let t = i / 180 * Math.PI
let r = Math.sin(2 * t) * Math.cos(2 * t)
data.push([r, i])
}
return {
polar: {
title: {
text: 'Demo'
},
legend: {
data: ['line']
},
polar: {
center: ['50%', '54%']
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
}
},
angleAxis: {
type: 'value',
startAngle: 0
},
radiusAxis: {
min: 0
},
series: [
{
coordinateSystem: 'polar',
name: 'line',
type: 'line',
showSymbol: false,
data: data
}
],
animationDuration: 2000
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/echarts#4.1.0/dist/echarts.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-echarts#4.0.2"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<v-chart :options="polar"/>
</div>

Set filter options on vue-good-table programmatically

How can one change the value that is displayed in the UI filter elements(input, dropdown etc) in vue-good-table programmatically?
For example if I call:
this.$set(this.table.columnsFilters, 'name', 'bob')
I want the value in the HTML input field 'name' to display bob.
Unfortunatly the settting the values as i described above does not work
Edit If you are using version 2.16.0 or above, you'll need to do this:
CodePen for v2.16.0 +
// v2.16.0 or higher
...
changeFilter(field, newFilter) {
let newCols = JSON.parse(JSON.stringify(this.columns));
let found = newCols.find(c => {
return c.field == field;
});
console.log(found);
if (found) {
if (found.hasOwnProperty("filterOptions")) {
found.filterOptions.filterValue = newFilter;
this.columns = newCols;
} else {
alert(`Column '${field}' does not have filtering configured!`);
}
} else {
alert(`Field '${field}' does not exist!`);
}
}
Original Answer
If I am understanding this correctly you want to set the filter for a field programmatially... Something like this should work.. Click the button to change the filter programamaticlly... If you change this line to any valid name, it will filter by that name... Change 'Bob' to a valid name...(like Dan)...
<button
style="width:200px;"
#click.stop="changeFilter('name', 'Bob')"
>Click To Change Name Filter</button>
CodePen Mirror
const vm = new Vue({
el: "#app",
name: "my-component",
data: {
columns: [
{
label: "Name",
field: "name",
filterOptions: {
enabled: true, // enable filter for this column
placeholder: "Filter Name", // placeholder for filter input
filterValue: "", // initial populated value for this filter
filterDropdownItems: [], // dropdown (with selected values) instead of text input
filterFn: this.columnFilterFn, //custom filter function that
trigger: "enter" //only trigger on enter not on keyup
}
},
{
label: "Age",
field: "age",
type: "number"
},
{
label: "Created On",
field: "createdAt",
type: "date",
dateInputFormat: "YYYY-MM-DD",
dateOutputFormat: "MMM Do YY"
},
{
label: "Percent",
field: "score",
type: "percentage"
}
],
rows: [
{
id: 1,
name: "John",
age: 20,
createdAt: "201-10-31:9: 35 am",
score: 0.03343
},
{
id: 2,
name: "Jane",
age: 24,
createdAt: "2011-10-31",
score: 0.03343
},
{
id: 3,
name: "Susan",
age: 16,
createdAt: "2011-10-30",
score: 0.03343
},
{
id: 4,
name: "Bob",
age: 55,
createdAt: "2011-10-11",
score: 0.03343
},
{
id: 5,
name: "Dan",
age: 40,
createdAt: "2011-10-21",
score: 0.03343
},
{
id: 6,
name: "John",
age: 20,
createdAt: "2011-10-31",
score: 0.03343
}
]
},
methods: {
clearFilter(field) {
try {
let found = this.columns.find((c) => {
return c.field == field
});
found.filterOptions.filterValue = "";
} catch {
alert(`Unable to clear ${field} filter`)
}
},
changeFilter(field, newFilter) {
let found = this.columns.find((c) => {
return c.field == field
});
if(found) {
if(found.hasOwnProperty("filterOptions")) {
if(found.filterOptions.hasOwnProperty("filterValue")) {
found.filterOptions.filterValue = newFilter;
} else {
alert(`Column '${field}' does not have filterValue property!`)
}
} else {
alert(`Column '${field}' does not have filtering configured!`)
}
} else {
alert(`Field '${field}' does not exist!`)
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-good-table#2.15.3/dist/vue-good-table.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vue-good-table#2.12.2/dist/vue-good-table.css" rel="stylesheet"/>
<div id="app">
<div>
<div style="margin:10px 10px 10px 10px;">
<button
style="width:200px;"
#click.stop="changeFilter('name', 'Bob')"
>Click To Change Name Filter</button>
<button
style="width:200px;"
#click.stop="clearFilter('name')"
>Clear Name Filter</button>
</div>
<vue-good-table :columns="columns" :rows="rows" />
</div>
</div>
See: https://github.com/xaksis/vue-good-table/issues/475
Official recommended method of doing this for version >= 2.17.5:
this.$set(this.columns[foundIndex].filterOptions, 'filterValue', value);
If you want to have it done using $route query params:
for (var key in this.$route.query){
var field = key;
let foundIndex = this.columns.findIndex((c) => {
return c.field == field
});
if (foundIndex !== -1 ){
this.$set(this.columns[foundIndex].filterOptions, 'filterValue', this.$route.query[key]);
}
}
Vue cannot detect normal property additions (e.g. this.myObject.newProperty = 'hi')
Therefore, using this.$set(this.table.columnsFilters, 'name', 'bob') instead of your code.
More information about $set

Kendo Change SeriesDefault Chart Type Dynamically

The Code works But I wanna Change Chart Type Dynamically. I tried Change Chart Type in function WeightLine However It does not work. It changes SeriesDefault type , I see new chart type in alert but does not draw new chart type.
var mydata=[{"date":"2013-03-06","data":2916,"name":"weight"},{"date":"2013-03-05","data":3708,"name":"weight"}];
function getFilter(xMin, xMax) {
return [{
field: "date",
operator: "gt",
value: xMin
}, {
field: "date",
operator: "lt",
value: xMax
}];
}
$("#line_chart_weight").kendoChart({
title: {
text: "weight"
},
dataSource:{
data: mydata,
group: {
field: "name"
},
sort: {
field: "date",
dir: "asc"
},
schema: {
model: {
fields: {
date: {
type: "date"
}
}
}
}
},
seriesDefaults: {
type: "scatterLine"
},
series: [{
xField:"date",
yField: "data"
}],
yAxis: {
labels: {
format: "{0}"
},
title: {
text: "KG",
padding: {
left: 20
}}
}, xAxis: {
labels:
{
rotation: -90,
format:"dd-MM-yyyy"
},
title: {
text: "Date",
padding: {
top: 20
}},
type:"date",
name:"CategoryAxis"
},
tooltip: {
visible: true,
format:"dd-MM-yyyy",
color:"white"
},
transitions: false,
drag: onDragw,
zoom: onDragw
});
var weight=$("#line_chart_weight").data("kendoChart");
function onDragw(e) {
var ds = weight.dataSource;
var options = weight.options;
e.originalEvent.preventDefault();
var categoryRange = e.axisRanges.CategoryAxis;
if (categoryRange) {
var xMin = categoryRange.min;
var xMax = categoryRange.max;
options.categoryAxis.min = xMin;
options.categoryAxis.max = xMax;
ds.filter(getFilter(xMin, xMax));
weight.redraw();
}
}
function WeightLine(WeightTypeString){ weight.options.seriesDefaults.type=WeightTypeString;alert(weight.options.seriesDefaults.type); weight.redraw();}
it is a bit weird but i write something to solve this. both of them worked for me. You can modify them for your code.
1.
var chart = $("#chartId").data("kendoChart");
chart.setOptions({ seriesDefaults: {type : "radarColumn"} });
chart.dataSource.read();
chart.refresh();
2.
var chart = $("#chartId").data("kendoChart");
for(i = 0; i< chart.options.series.length;i++){
chart.options.series[i].type = "radarColumn";
}
chart.refresh();