繁体   English   中英

在Javascript中使用Razor(非MVC)

[英]Using Razor inside Javascript (not MVC)

我想知道我是否可以在javascript中使用剃须刀!

<html>
    <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the corechart package.
    google.charts.load('current', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(drawChart);

    // Callback that creates and populates a data table,
    // instantiates the pie chart, passes in the data and
    // draws it.
    function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
          ['Mushrooms', 3],
          ['Onions', 1],
          ['Olives', 1],
          ['Zucchini', 1],
          ['Pepperoni', 2]
        ]);

        // Set chart options
        var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
    </head>

    <body>
        <!--Div that will hold the pie chart-->
        <div id="chart_div"></div>
    </body>
</html>

这只是Google的基本代码,它将显示带有静态值的饼图,我想在图表中的数字上添加一些变量,以便它们可以根据我页面上的数据进行更改。

data.addRows([
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);

基本上,在这种情况下,这是很重要的部分,我想将这段代码中的数字交换为诸如@number类的剃须刀变量,这可能吗?

在搜索一些答案时,我发现添加javascript代码将使其允许剃须刀,但我无法使其工作,当我这样做时,仅通过添加<text>甚至没有任何剃须刀代码都无法显示图表。

或者,如果您有使用Google Charts API的经验,并且知道如何以更好的方式整体上做到这一点!

是的,您可以在<script>标记内使用razor

<script type="text/javascript">
  data.addRows([
    ['@someRazorString', @someRazorNumber]
  ]);
</script>

另外,您可以使用

@{
var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
<text>
    <script type="text/javascript">
        var someJsObjectOrArray = @Html.Raw(JsonConvert.SerializeObject(Model.someDotNetObjectOrArray, jsonSerializerSettings)));
    </script>
</text>
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM