Apostrophe issue in JavaScript with Razor - javascript

It's simple!
This is my dynamic JavaScript code with Razor markup:
<script type="text/javascript">
$.fancybox.open(
[
#foreach (var class in GenericClass)
{
var aux = "{ href: 'http://localhost:63095" + Url.RouteUrl("Image") + "' }";
<Text>#aux</text>
break;
}
],
{ helpers: { thumbs: { width: 75, height: 50 } }
});
</script>
This is what I get in any web browser:
<script type="text/javascript">
$.fancybox.open(
[
{ href: 'http://localhost:63095/Home/Image' }
],
{ helpers: { thumbs: { width: 75, height: 50 } }
});
</script>
But this is what I really wanted to be generated:
<script type="text/javascript">
$.fancybox.open(
[
{ href: 'http://localhost:63095/Home/Image' }
],
{ helpers: { thumbs: { width: 75, height: 50 } }
});
</script>
The problem is clear: instead of an apostrophe (') the output has '. Does someone know how I can generate the ' instead of ' ?
OBSERVATION: I already tried to do escaping and encoding but neither seems to work.

Maybe try including the value inline instead:
#foreach (var class in GenericClass)
{
<Text>{ href: 'http://localhost:63095#(Url.RouteUrl("Image"))' }</text>
break;
}
I believe that should fix the issue
Raw Html Approach
If you do need raw html you can use the following:
#Html.Raw(myString)
Just be very careful with this especially if you are including values entered by the user since it could cause XSS or other security issues.

Related

How to assign HTML element ID, through an Angular component, to a JavaScript function?

I found a JavaScript library and a function, I struggled, but did include this JavaScript function in my Angular application.
The JavaScript code prints takes in an object (myData: two arrays of numbers), and passes this data to a function, which draws two charts, each chart corresponds to one of the two arrays of numbers.
First thing I had to do is figure out how to include this JavaScript in my Angular project, which wasn't easy. And I'm even still not sure if it worked or not, because I haven't finished connecting everything together.
So here's the JavaScript code:
<!DOCTYPE html>
<html>
<head>
<!-- This page was last built at 2020-10-16 19:40 -->
<meta charset="utf-8"/>
<!-- Plotly.js -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div class="myDiv" id="myDiv">
</div>
<div class="myDiv" id="myDiv2">
</div>
<script>
myData = {
"loss": [
0.6437230565968681,
.
.
.
0.015016184188425541
],
"accuracy": [
0.6740923523902893,
.
.
.
0.9943200945854187
]
}
dataPlot(myData)
function dataPlot(myData){
function range(start, end) {
var ans = [];
for (let i = start; i <= end; i++) {
ans.push(i);
}
return ans;
}
yLoss = myData['loss'];
yAccuracy = myData['accuracy'];
traceLoss = {
type: 'scatter',
x: range(yLoss.length>0?1:0,yLoss.length),
y: yLoss,
mode: 'lines',
name: 'Red',
line: {
color: 'rgb(219, 64, 82)',
width: 1
}
};
traceAccuracy = {
type: 'scatter',
x: range(yAccuracy.length>0?1:0,yAccuracy.length),
y: yAccuracy,
mode: 'lines',
name: 'Blue',
line: {
color: 'rgb(55, 128, 191)',
width: 1
}
};
var layoutLoss = {
title: 'Model Binary Crossentropy Loss',
xaxis: {
title: 'Epochs',
showgrid: false,
zeroline: false
},
yaxis: {
title: 'Loss',
showline: false
}
// for static size
,width: 900,
height: 500
};
var layoutAccuracy = {
title: 'Model Training Data Accuracy',
xaxis: {
title: 'Epochs',
showgrid: false,
zeroline: false
},
yaxis: {
title: 'Accuracy',
showline: false
}
// for static size
,width: 900,
height: 500
};
var dataLoss = [traceLoss];
var dataAccuracy = [traceAccuracy];
divs('myDiv','myDiv2')
function divs(div1, div2) {
Plotly.newPlot(div1, dataLoss, layoutLoss);
Plotly.newPlot(div2, dataAccuracy, layoutAccuracy);
}
}
</script>
</body>
</html>
If you copy that code to a .html file it'll work.
See at the bottom of the code this function:
function divs(div1, div2) {
Plotly.newPlot(div1, dataLoss, layoutLoss);
Plotly.newPlot(div2, dataAccuracy, layoutAccuracy);
}
This function takes div1 and div2 values, those are the IDs for the 2 divs containing the charts.
What I need is, first, to pass myData to the function, which is easy and doable, not a problem.
The problem is, how am I supposed to give the IDs of the divs to the JavaScript function, and have it know where those divs are to begin with?
I've been trying with #ViewChildren and ElementRef. But no success.
Here's my HTML template so far:
<div #divs *ngFor="let item of [1,2]" [id]="'myDiv-' + item">Div {{item}}+{{whatevs}}</div>
<button (click)="getDivs()">Get divs</button>
and the component:
import { Component, ElementRef, OnInit, QueryList, ViewChildren } from '#angular/core';
declare var dataPlot: any;
#Component({
selector: 'jhi-ml-model-data',
templateUrl: './ml-model-data.component.html',
})
export class MlModelDataComponent implements OnInit {
#ViewChildren("divs", { read: ElementRef }) divs!: QueryList<ElementRef>;
myData: any;
constructor() { }
getDivs(): void {
// this.divs.forEach((div: ElementRef) => div.nativeElement);
this.divs.forEach((div: ElementRef) => console.log(div.nativeElement.getAttribute('id')));
// this^ gets the IDs for both divs, not each one individually.
}
ngOnInit(): void {
this.myData = {
"loss": [0.6437230565968681,
.
.
.
0.39040950554258685],
"accuracy": [0.6740923523902893,
.
.
.
0.9943200945854187]
}
dataPlot(this.myData);
dataPlot.divs();
}
}
I feel like I've put myself in an untangleable mess, and feel like there must be

How to display two C3 charts in the same row in two different divs

I've some problems with c3 plugins.
I'm trying to put 2 charts in a structure like this:
<div class="row">
<div class="col-6">
<div id="chart1"></div>
</div>
<div class="col-6">
<div id="chart2"></div>
</div>
</div>
My output is the attached one, and i couldn't find the reason why the charts go out of the div.
I've already tried to use chart.resize() but it doesn't work (maybe i put it in the wrong place).
Can you help me ?
You can find my code here:
js1, js2, html
Thank you !
The problem is that you are loading the charts (I think!) within a div that is not displayed when the page loads, the C3 doesn't know how to size the charts correctly.
Instead of loading every chart in the Document Ready, wrap your posts in a function like this:
function loadStatArticoliCharts() {
$.post(
'{{ url('myGetter') }}/{{ data.listId }}',
{},
function(data) {
grafico_fatturato = c3.generate({
bindto: "#fatturato-mensile-barre",
data: {
columns: [
[new Date().getFullYear() - 1, 0,0,0,0,0,0,0,0,0,0,0,0],
[new Date().getFullYear(), 0,0,0,0,0,0,0,0,0,0,0,0],
],
type : 'bar',
colors: data.colors
},
bar: {
width: 30
},
axis: {
x: {
type: 'category',
categories: months
},
y: {
tick: {
format: function(value) { return value.formatMoney(2, ',', '.') }
}
}
},
tooltip: {
format: {
value: function(value) { return "€ " + value.formatMoney(2, ",", "."); }
}
},
transition: {
duration: 1000
}
});
setTimeout(function() {
grafico_fatturato.load({
columns: [
data.columns.current,
data.columns.past
],
});
grafico_fatturato.resize();
}, 500);
}
);
}
Create a global boolean variable to store if you've already loaded the charts (so you won't trigger the load multiple times) with
let loadedChart1 = false;
let loadedChart2 = false;
Finally create a controller that will trigger the load function when you click the tab:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (ev) {
let tabId = $(ev.target).attr("aria-controls");
switch (tabId) {
case "chart1":
if (!loadedChart1) {
loadChart1();
loadedChart1 = true;
}
break;
case "chart2":
if (!loadedChart2) {
loadChart2();
loadedChart2 = true;
}
break;
}
let oldTabId = $(ev.relatedTarget).attr("aria-controls");
$('#' + oldTabId).removeClass("active");
}

tinyMCE 4.x - restore default formatting after inserting html

I created an initial version of a plugin for inserting footnotes in tinyMCE, basing on some resources that I found for WordPress and Drupal. Here's the code:
tinymce.PluginManager.add('footnotes', function(editor) {
function showDialog() {
var win = editor.windowManager.open({
title: "Add a footnote",
id: 'footnote-dialog',
body: {
type: 'textbox',
name: 'footnote',
multiline: true,
minWidth: 520,
minHeight: 100,
//style: 'direction: ltr; text-align: left'
},
onSubmit: function(e) {
e.preventDefault();
var footnote = e.data.footnote;
if (footnote.length){
var html = '<span><sup class="footnote-elem" data-toggle="tooltip" data-placement="top" title="'+footnote+'">[*]</sup></span>';
editor.undoManager.transact(function() {
tinyMCE.activeEditor.execCommand('mceInsertRawHTML', false, html);
});
editor.windowManager.close();
}
}
});
}
editor.addButton("footnotes", {
title : 'Insert a footnote',
image : tinyMCE.baseURL + '/plugins/footnotes/img/note_add.png',
onclick: showDialog
});
});
the plugin basically works:
the problem is that the following inserted text is inserted as <sup> too:
So the desired behaviour would be:
put the cursor immediately after the inserted html;
restore original formatting.
Any suggestion/help on how to achieve that?
Thanks

SyntaxError: missing : after property id in angularJs

I'm new in angularJs, i have javascript which contains to load the applet.
that is working in javascript but when I'm putting same code in angularJs, that is not compiling, my script is not executing, for that i wrote a custom directive, but that is giving error SyntaxError: missing : after property id.
Java Script:
<div id="appletbox" class="photobox">
<script src="https://www.java.com/js/deployJava.js"></script>
<script>
var attributes = {
id: "fingerCaptureApplet",
width: 140,
height: 140
};
var parameters = {
jnlp_href: "fca/finger-capture-applet.jnlp"
};
deployJava.runApplet(attributes, parameters, '1.7');
</script>
</div>
Custom Directive Code:
angular.module('some', ['ngRoute'])
.directive('fingerScanner', function() {
return {
var attributes = {
id: "fingerCaptureApplet",
width: 140,
height: 140
};
var parameters = {
jnlp_href: "fca/finger-capture-applet.jnlp"
};
deployJava.runApplet(attributes, parameters, '1.7');
};
});
using that directive is like below:
<div finger-scanner/>
please whether I'm doing right way or anything wrong.
Thanks.
You're returning an object. However, it seems like you're just trying to run the deployJava code.
To do this, place your desired function in a link property:
Replace:
return {
var attributes = {
id: "fingerCaptureApplet",
width: 140,
height: 140
};
var parameters = {
jnlp_href: "fca/finger-capture-applet.jnlp"
};
deployJava.runApplet(attributes, parameters, '1.7');
};
With:
return {
link: function(){
var attributes = {
id: "fingerCaptureApplet",
width: 140,
height: 140
};
var parameters = {
jnlp_href: "fca/finger-capture-applet.jnlp"
};
deployJava.runApplet(attributes, parameters, '1.7');
}
};
I believe your return is incorrect in your custom directive. You're returning an object but formatting the properties and methods like you would normal variables and functions. Remember that for objects, all properties are key value pairs (whether the value be another object, function, variable, etc.). Try reformatting your object like so:
angular.module('some', ['ngRoute'])
.directive('fingerScanner', function() {
return {
attributes: {
id: "fingerCaptureApplet",
width: 140,
height: 140
},
parameters: {
jnlp_href: "fca/finger-capture-applet.jnlp"
},
appletResults: deployJava.runApplet(this.attributes, this.parameters, '1.7')
};
});

Write new data into javascript variable and parse JSON

I have this code which help me to show Verite Timeline on my page so:
<div id="timeline-embed"></div>
<script type="text/javascript">
var timeline_config = {
width: "100%",
height: "100%",
debug: true,
rows: 2,
source: {
"timeline":
{
"headline":"Sh*t People Say",
"type":"default",
"text":"People say stuff",
"startDate":"10/4/2011 15:02:00",
"date": [
{
"startDate":"10/4/2011 15:10:00",
"endDate":"10/4/2011 15:55:00",
"headline":"FIRST",
"text":"<p>FIRSTTEXT</p>",
"asset":
{
"caption":"yessss"
}
},
{
"startDate":"10/4/2011 17:02:00",
"endDate":"10/4/2011 18:02:00",
"headline":"SECOND",
"text":"<p>In true political fashion, his character rattles off common jargon heard from people running for office.</p>",
"asset":
{
"media":"http://youtu.be/u4XpeU9erbg",
"credit":"",
"caption":""
}
}
]
}
}
}
</script>
so Now on source: into date I want to add new element:
{
"startDate":"CurrentDate + zajson",
"endDate":"10/4/2011 18:02:00",
"headline":"place.name",
"asset":
{
"media":"http://youtu.be/u4XpeU9erbg",
"credit":"",
"caption":""
}
}
so offcource I have a variable:
var place.name;
var zajson;
and When I click on <button>Add to timeline</button> I want to add new element (as i show above) into source: in date, as new block of values ...
Is it posible to do this?
And how I can update source: and run it again when I add new block of data???
sorry for my english
function addContent() {
var content = {
"startDate":"CurrentDate + zajson", // <-- these two probably shouldn't be in quotes, but concated
"endDate":"10/4/2011 18:02:00",
"headline":"place.name", // <-- this one, too
"asset":
{
"media":"http://youtu.be/u4XpeU9erbg",
"credit":"",
"caption":""
}
};
timeline_config.source.timeline.date.push(content);
}
Something like this should do it.
Then, for the button:
<button onclick="addContent()">Add to timeline</button>

Categories

Resources