KendoUI: Unable to bind data to HTML elements from JSON file. - mvvm

I am new to kendo ui and mvvm, and I'm facing this issue:
I'm having a JSON file in the follow format:
[
{
"Id":1,
"img":"shoes.png"},
{"Id":2,
"img":"books.png"}
}
]
I am reading the file using the sample mentioned online by kendo guys as follows:
var crudServiceBaseUrl = "pro.json";
var viewModel = kendo.observable({
productsSource: new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl,
dataType: "json"
},
update: {
url: crudServiceBaseUrl,
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl,
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
return options;
}
},
batch: true,
schema: {
model: {
id: "Id"
}
}
})
});
kendo.bind($("#form-container"), viewModel);
I am able to bind the data from the data source to a Kendo Control such as a dropdownlist or some other Kendo Control. But when I try binding the data to an HTML Control (mostly an img tag). It stops working and gives an error saying "this.parent" is not a function.
following is the HTML which works:
Select Product: <select data-role="dropdownlist" data-value-field="Id" data-text-field="img"
data-bind="source: productsSource"></select>
However binding to a normal <img> tag does not work. In short I need to bind images based on src value to a div using kendo ui mvvm.
Kindly help me out. Thanks!!
-
Hardik

Currently Kendo MVVM cannot bind a data source to an HTML element. Only Kendo UI widgets can be bound to a kendo.data.DataSource. Using a widget e.g. the ListView would work for a DIV:
<div data-role="listview"
data-template="template"
data-bind="source: productsSource">
</div>
<script id="template" type="text/x-kendo-template">
<img data-bind="attr: { src: img }" />
</script>

Related

vue-chartjs and custom legend using generateLegend()

The generateLegend() wrapper does call the legendCallback defined in my Vue code but I'm lost to how to render the custom HTML in vue-chartjs. What do I do with htmlLegend as described in the vue-chartjs api docs like here.
Here is the line chart component I'm trying to render with a custom HTML object.
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins
export default {
extends: Line,
mixins: [reactiveProp],
props: ['chartData','options'],
data: () => ({
htmlLegend: null
}),
mounted () {
this.renderChart(this.chartData, this.options);
this.htmlLegend = this.generateLegend();
}
}
Here is my vue template
<template>
<div class="col-8">
<line-chart :chart-data="datacollection" :options="chartOptions"></line-chart>
</div>
</template>
Well, htmlLegend holds the markup of the generated legend... so you can just put it into your tag via v-html
<template>
<div class="col-8">
<div class="your-legend" v-html="htmlLegend" />
<line-chart :chart-data="datacollection" :options="chartOptions"></line-chart>
</div>
</template>
mounted() {
this.renderChart( this.chartData , this.options );
var legend = this.generateLegend();
this.$emit('sendLegend', legend)
}
and then in the vue file add a new div to show the legend and also listen to the event to get the legend data
<div class="line-legend" v-html="chartLegend"></div>
<line-chart #sendLegend="setLegend" :chart-data="datacollection" :options="chartOptions"></line-chart>
and also add this to the data
chartLegend: null,
and you also need a method
setLegend (html) {
this.chartLegend = html
},

How To Properly Initialize Form Data In Vue

so I have a component that is rendering a form and it also is pre-filling the fields with data received from ajax request.
My issue is that I want to not only be able to edit fields but also add new fields to submit at the same time, so because of this I am trying to initialize my pre-filled data and new data into the same Object to be submitted with my ajax request. With my current set up the form-data is not consistently filling in the fields before the form is rendered.
This is the form template
<form #submit.prevent="editThisWorkflow" class="d-flex-column justify-content-center" >
<div>
<input type="text" v-model="workflowData.workflow">
</div>
<div >
<div v-for="object in workflowData.statuses" :key="object.id">
<input type="text" v-model="object.status">
</div>
<div v-for="(status, index) in workflowData.newStatuses" :key="index">
<input type="text" placeholder="Add Status" v-model="status.value">
<button type="button" #click="deleteField(index)">X</button>
</div>
<button type="button" #click="addField">
New Status Field
</button>
</div>
<div>
<div>
<button type="submit">Save</button>
<router-link :to="{ path: '/administrator/workflows'}" >Cancel</router-link>
</div>
</div>
</form>
This is the script
data() {
return {
workflowData: {
id: this.$store.state.workflow.id,
workflow: this.$store.state.workflow.workflow,
statuses: this.$store.state.workflow.statuses,
newStatuses: []
},
workflowLoaded: false
}
},
computed: {
...mapGetters(['workflow']),
},
methods: {
...mapActions(['editWorkflow']),
editThisWorkflow() {
this.editWorkflow({
id: this.workflowData.id,
workflow: this.workflowData.workflow,
statuses: this.workflowData.statuses,
newStatuses: this.workflowData.newStatuses
})
},
addField() {
this.workflowData.newStatuses.push({ value: ''});
},
deleteField(index) {
this.workflowData.newStatuses.splice(index, 1);
}
And this is the store method to submit the data
editWorkflow(context, workflowData) {
axios.patch('/workflowstatuses/' + workflowData.id, {
workflow: workflowData.workflow,
statuses: workflowData.statuses,
newStatuses: workflowData.newStatuses
})
.then(response => {
context.commit('editWorkflow', response.data)
})
.catch(error => {
console.log(error.response.data)
})
},
My problem comes in here
data() {
return {
workflowData: {
id: this.$store.state.workflow.id,
workflow: this.$store.state.workflow.workflow,
statuses: this.$store.state.workflow.statuses,
newStatuses: []
},
workflowLoaded: false
}
},
Is there a better way to set this part??
workflowData: {
id: this.$store.state.workflow.id,
workflow: this.$store.state.workflow.workflow,
statuses: this.$store.state.workflow.statuses,
newStatuses: []
},
If you only need to assign store values to your form once then you can use mounted function.
mounted: function() {
this.id = this.$store.state.workflow.id
this.workflow = this.$store.state.workflow.workflow
this.statuses = this.$store.state.workflow.statuses
},
data() {
return {
workflowData: {
id: '',
workflow: '',
statuses: '',
newStatuses: []
},
workflowLoaded: false
}
},
the data property does not accept this, I usually use arrow function in this question because it prohibits me from using this, and prohibits my team from also using this within the data.
Declare all necessary items within the datato maintain reactivity, and assign the value within the mounted of the page.
mounted() {
this.workflowData.id = this.$store.state.workflow.id
this.workflowData.workflow = this.$store.state.workflow.workflow
this.workflowData.statuses = this.$store.state.workflow.statuses
},
data: () => ({
workflowData: {
id: '',
workflow: '',
statuses: '',
newStatuses: []
},
workflowLoaded: false
}
},
})
The way how I resolved this problem turned out to be simpler than most of the solutions presented here. I found it hard to reach data from this.$store.state due to Vuejs life cycle. And assigning values to v-mode tourned out to be impossible because "v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth."
Solution
To pre-fill the field with data received from ajax request e.g. input field of type email I did as follow.
1st. I saved the output of my ajax request in application's storage (Cookies) -it can be Local Storage or Session, depended what is appropriate to you.
2nd. I populated my Vuex's store (single source of truth) with the data from my application storage. I do it every time when I reload a page.
3rd. Instead of binding a data to v-model in Vuejs life cycle, or using value attribute of html input (<input type="email" value="email#example.com">). I Pre-filled input by populating placeholder attribute of html with data coming from Vuex store like this:
<input v-model="form.input.email" type="email" name="email" v-bind:placeholder="store.state.user.data.email">

ag-Grid javaScript, TypeError: rowData is undefined

ag-Grid, following the official demo of javascript but using API like real world over hard-coded data. Note: no jQuery, just use the primitive plain XMLHttpRequest() for ajax.
F12 verified API returns data in the same structure as demo, has children node inside, and gripOptions.rowData is assigned with the returned data.
Tried instantiating rowData inside of gripOptions as
rowData: [], got the same error
Or
rowData: {}, got ReferenceError: rowData is not defined.
HTML:
<script src="/scripts/agGrid/ag-grid.js"></script>
<script src="/scripts/agGrid/myAG.js"></script>
<br />JavaScript ag-Grid
<div id="myGrid" style="height: 200px;" class="ag-fresh"></div>
myAG.js:
var httpApi = new XMLHttpRequest();
var columnDefs = [
{ headerName: "Client Name", field: "ClientName", unSortIcon: true, cellRenderer: "group" },
{ headerName: "Division", field: "Division" },
{ headerName: "Others", field: "Others" }
];
var gridOptions = {
columnDefs: columnDefs,
getNodeChildDetails: getNodeChildDetails
};
function getNodeChildDetails(rowItem) {
if (rowItem.ClientName) {
return {
group: true,
// provide ag-Grid with the children of this group
children: rowItem.children,
// the key is used by the default group cellRenderer
key: rowItem.ClientName
};
} else {
return null;
}
}
// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function () {
$.ajax({
type: "GET",
url: "/api/myAG/Tree",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
gridOptions.rowData = data;
var eGridDiv = document.querySelector('#myGrid');
new agGrid.Grid(eGridDiv, gridOptions);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
})
});
Version:
ag-grid = v8.1.0
FireFox = 50.1.0
Error message:
F12 confirms data exists and assigned:
inside of ag-grid.js, the line it complains about but rowData has data:
See this answered post, basically an additional check is needed for the tree.
ag-Grid, try to make Tree Demo work using own data

knockoutjs mapping select data-bind options

I am having problems binding the selected value of a selectbox to a property within the view model. For some reason it keeps coming back unchanged when posted back to the server.
My Html is:
<form action="/Task/Create" data-bind="submit: save">
<table border="1">
<tr>
<td>ref type</td>
<td><select data-bind="options: ReferenceTypes, optionsText: 'Name', optionsCaption: 'Select...', value:Task.ReferenceTypeId"></select></td>
<td>Reference</td>
<td><input data-bind="value:Task.Reference" /></td>
</tr>
</table>
<button type="submit">Save Listings</button>
</form>
The Javascript is:
<script type="text/javascript">
var viewModel = {};
$.getJSON('/Task/CreateJson', function (result) {
viewModel = ko.mapping.fromJS(result.Data);
viewModel.save = function () {
var data = ko.toJSON(this);
$.ajax({
url: '/Task/Create',
contentType: 'application/json',
type: "POST",
data: data,
dataType: 'json',
success: function (result) {
ko.mapping.updateFromJS(viewModel, result);
}
});
}
ko.applyBindings(viewModel);
});
</script>
JSON from Fiddler that gets loaded into the page as below.
{
"ContentEncoding":null,
"ContentType":null,
"Data":{
"Task":{
"ReferenceTypeId":0,
"Reference":"Default Value"
},
"ReferenceTypes":[
{
"Id":2,
"Name":"A Ref Type"
},
{
"Id":3,
"Name":"B Ref Type"
},
{
"Id":1,
"Name":"C Ref Type"
}
]
},
"JsonRequestBehavior":1
}
This comes back into the server (ASP.NET MVC3) correctly, with the updated Reference string value, but ReferenceTypeId is not bound to the correctly selected drop down value. Do I need to perform any additional functions to bind correctly etc? Or tell the data-bind what the select value column is (Id) etc? I have checked in Fiddler on the values getting posted back from the browser, and it has the same original value (0). So it is definately not the server.
I hope someone can help, if you need any further information please ask.
Kind Regards
Phil
The issue is that your options binding will try to assign the object that it is bound to, to the value observable specified.
For example if you select "A Ref Type" the options binding will push the json object
{ "Id":2, "Name":"A Ref Type" }
Into your Task.ReferenceTypeId observable which will then be serialized back to your server. In this case you need to add an optionsValue config options to tell the binding just to save the id.
<select data-bind="options: ReferenceTypes, optionsText: 'Name',
optionsCaption: 'Select...', optionsValue: 'Id', value:Task.ReferenceTypeId">
</select>
Here's an example.
http://jsfiddle.net/madcapnmckay/Ba5gx/
Hope this helps.

How to export kendoui dataviz chart to (.png) or (.jpg) image format by poping up Save-As window?

I am using kendoui dataviz charts, and I need to export those charts into (.png) or (.jpg) image format.
Basically kendoui dataviz chart has a built-in method called 'svg()'.
'svg()' Returns the SVG representation of the current chart. The returned string is a self-contained SVG document.
Example
var chart = $("#chart").data("kendoChart");
var svgText = chart.svg();
Now svgText contains details of chart image..can anybody tell me how to convert these data to actual image format and pop up a Save As prompt ???
code example: I tried this, but it doesn't prompt any 'SaveAs' popup
<div id="example" class="k-content">
<div class="chart-wrapper">
<div id="chart"></div>
<center>
<div>
<input type="button" value="click" onclick="disp();" />
</div>
</center>
<div>
<canvas id="canvas"></canvas>
</div>
</div>
</div>
<script type="text/javascript">
function disp() {
var chart = $("#chart").data("kendoChart");
var svgText = chart.svg();
var c = document.getElementById('canvas');
canvg(c,svgText);
var img = c.toDataURL("image/png");
document.write('<img src="' + img + '"/>');
window.win = open(imgOrURL);
setTimeout('win.document.execCommand("SaveAs")', 100);
}
function createChart() {
$("#chart").kendoChart({
theme: $(document).data("kendoSkin") || "default",
title: {
text: "Internet Users"
},
legend: {
position: "bottom"
},
chartArea: {
background: ""
},
seriesDefaults: {
type: "bar"
},
series: [{
name: "World",
data: [15.7, 16.7, 20, 23.5, 26.6]
}, {
name: "United States",
data: [67.96, 68.93, 75, 74, 78]
}],
valueAxis: {
labels: {
format: "{0}%"
}
},
categoryAxis: {
categories: [2005, 2006, 2007, 2008, 2009]
},
tooltip: {
visible: true,
format: "{0}%"
}
});
}
$(document).ready(function () {
setTimeout(function () {
createChart();
},100);
$(document).bind("kendo:skinChange", function (e) {
createChart();
});
});
<script>
UPDATE 2
The Chart now includes various export options - PNG, SVG and a vector PDF. See the Export demo for reference.
UPDATE
The Chart now has built-in method for obtaining the exported image (base64 encoded):
var img = chart.imageDataURL();
I'm not aware of a cross-browser way to display a "Save As" dialog.
See also: API Reference
Original response follows:
Exporting the Chart image in-browser is not possible. We have prepared a demo that shows how to convert the SVG document to PNG/PDF on the server using Inkscape.
The demo application is implemented in ASP.NET MVC, but does not depend on any of its features and can be ported to other frameworks.
You can find the demo on GitHub:
https://github.com/telerik/kendo-examples-asp-net/tree/master/chart-inkscape-export
U can do like this.
For this approach u need svg.dll
U can download from this link.
http://svg.codeplex.com/releases/view/18884
Javascript:
var chart = $("#chart").data("kendoChart");
var svgString = escape(chart.svg());
$.ajax({
url: "/MyController/Sample",
data: { svg: svgString },
async: false,
type: 'Post',
success: function (data) {
window.location = "/MyController/getPdf";
}
});
Controller:
[HttpPost]
[ValidateInput(false)]
public void Sample(string svg)
{
var svgText = System.Web.HttpUtility.UrlDecode(svg);
Session["chrtData"] = svgText;
}
public void getPdf()
{
string svgText = Session["chrtData"].ToString();
var byteArray = Encoding.ASCII.GetBytes(svgText);
using (var stream = new MemoryStream(byteArray))
{
var svgDocument = Svg.SvgDocument.Open(stream);
//First Way
var bitmap = svgDocument.Draw();
MemoryStream docMemStream = new MemoryStream();
bitmap.Save("D:\\hi.png", System.Drawing.Imaging.ImageFormat.Png);
}
}