How to consume Razor data in a javascript file

Asked

Viewed 11 times

0

I’m new around here, I’m trying to consume Razor data inside a js file. From what I understand the two languages do not communicate so I would need an alternative that does intermediation, taking the data from Razor to javascript, but I do not know how to apply it.

My script:

google.charts.load('current', { 'packages': ['corechart'] });

google.charts.setOnLoadCallback(drawChart);

Function drawChart(data) {

if (dados === undefined)
    dados = "**@Html.Raw(Model.GraficoColaboradores.JsonDados)**";

var obj = eval(dados);

var data = new google.visualization.DataTable();
data.addColumn('string', 'Unidades');
data.addColumn('number', 'Colaboradores');
data.addRows(obj);

var options = {
    chartArea: {
        'width': '80%',
        'height': '80%'
    },
    legend: { position: "none" },
};

var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);

}

1 answer

0

You can put the script on the cshtml page inside the tag <script>, then you use the tag <text> for the compiler to understand that it is not C#:

<script>
<text>
if (dados === undefined)
    dados = "**@Html.Raw(Model.GraficoColaboradores.JsonDados)**";

var obj = eval(dados);

var data = new google.visualization.DataTable();
data.addColumn('string', 'Unidades');
data.addColumn('number', 'Colaboradores');
data.addRows(obj);

var options = {
    chartArea: {
        'width': '80%',
        'height': '80%'
    },
    legend: { position: "none" },
};

var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);

</text>
</script>

Just be careful when you compare it to < within the tag <text> compiler will understand that it is opening a tag. Simple solution is to reverse, for example, if a < b flipped b > a, accordingly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.