Search code examples
javascripthtmlasp.net-mvc-4viewbag

How to include ViewBag value into javascript in view of controller


I have a controller view in an ASP.NET-MVC4 application, in which I have put a javascript for plotting purposes.

I want to get the value of ViewBag into that script. But it does not work.

google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);

function drawChart() {
    var number =  @(Model.Last().Energie_E_Maschine_kwh).ToString("F2", CultureInfo.InvariantCulture);  

    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work', number],
      ['Eat', 2],
      ['Commute', 2],
      ['Watch TV', 2],
      ['Sleep', 7]
    ]);

    var options = {
        title: 'My Daily Activities'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
}

Here ViewBag.test is my value that I want to access from the controller. When I print or use the value of ViewBag outside the script, it works fine.

Number conversion from German to standard:

['Work', @(Model.Last().Energie_E_Maschine_kwh).toString("G2", CultureInfo.InvariantCulture)],

Solution

  • Put the quatations: var number = @(Model.Last().Energie_E_Maschine_kwh).ToString("F2", CultureInfo.InvariantCulture);