如何将变量从Razor传递给JavaScript?

时间:2017-05-23 18:49:20

标签: javascript c# charts

我有一个C#变量“value”,我想传递给JavaScript Chartjs数据对象。它呈现图表但不包括两个@p值。请参阅下面的代码源:

cshtml文件:

@{
    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文件:

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
    }
);

如何编写它以使其有效?

3 个答案:

答案 0 :(得分:4)

如下所示

查看:

@{
   var p1 = 43;
   var p2 = 45
}


<input type="hidden" id="PassingToJavaScript1" value=@p1>
<input type="hidden" id="PassingToJavaScript2" value=@p2>

JavaScript的:

var p1 = document.getElementById('PassingToJavaScript1').value;
var p2 = document.getElementById('PassingToJavaScript2').value;

答案 1 :(得分:3)

你可以做到

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

并使用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]
            }
        ]
    };

在这种情况下,您不必使用隐藏的html字段,您可以扩展代码以使用更多字段,例如

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

答案 2 :(得分:2)

使用隐藏字段来保存值,然后从JavaScript中读取隐藏字段的值。

示例:

@{
    int p = 43;

}

<!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>
        <input type="hidden" id="someId" value="@p" />
    </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>

JS

var chart = document.getElementById("lineChart");
var hiddenFieldValue = document.getElementById("someId").value;

var data = {
    labels: [2012, 2013, 2014, 2015, 2016, 2017],
    datasets: [
        {
            label: "My Chart Label",
            fill: false,
            lineTension: 0.1,
            data: ['(hiddenFieldValue)', 45, 50, 48, 47, 52]  // Not really sure how to format the data but you get main idea...
        }
    ]
};

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