Saturday, June 1, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  175] [ 6]  / answers: 1 / hits: 19444  / 7 Years ago, tue, may 23, 2017, 12:00:00

I have one C# variable value that I want to pass into JavaScript Chartjs data object. It renders the chart but does not include the two @p values. See code source below:



cshtml file:



@{
int p1 = 43;
int p2 = 45;


}

<!DOCTYPE html>

<html>
<head>
<meta name=viewport content=width=device-width />
<title></title>
</head>
<body>
<div style=width: 400px;>
<canvas id=lineChart width=400 height=400></canvas>
</div>

<script src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js></script>
<script src=main.js></script>
</body>
</html>


javascript file:



var chart = document.getElementById(lineChart);

var data = {
labels: [2012, 2013, 2014, 2015, 2016, 2017],
datasets: [
{
label: My Chart Label,
fill: false,
lineTension: 0.1,
data: ['(@p1)', '(@p2)', 50, 48, 47, 52]
}
]
};

var lineChart = new Chart(chart,
{
type: 'line',
data: data
}
);


How can I write it so that it works?


More From » c#

 Answers
9

You can do



<script type=text/javascript>
var p1 = @p1, p2= @p2;
</script>


and use p1, p2.



  var data = {
labels: [2012, 2013, 2014, 2015, 2016, 2017],
datasets: [
{
label: My Chart Label,
fill: false,
lineTension: 0.1,
data: [p1, p2, 50, 48, 47, 52]
}
]
};


In this case you don't have to use hidden html fields and you can expand your code to use more field like



var tempObj ={
tempData: ,
otherData:,
moreData:
}

[#57684] Sunday, May 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darleneh

Total Points: 231
Total Questions: 110
Total Answers: 94

Location: Spain
Member since Thu, Dec 23, 2021
2 Years ago
;