2017-01-13 55 views
0

我想知道如果在我的情況下,我可以在JavaScript內使用剃鬚刀!在JavaScript(而不是MVC)中使用Razor

<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> 

這是谷歌只是一個基本的代碼,將顯示靜態值的餅圖,我想一些變量添加到數字的圖表中,使他們能夠基於我的頁面上的數據。

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

基本上,這是在這種情況下重要的部分,我想換號碼在此代碼剃刀例如像@number什麼的,這是可能的變量?

雖然搜索了一些答案,我發現在JavaScript代碼中添加將允許剃鬚刀,但我無法使它工作,當我做了圖表甚至沒有顯示,只需加入<text>,甚至沒有任何剃鬚刀碼。

或者如果您有使用Google Charts API的經驗,並知道如何以更好的方式做到這一點!

+0

作爲指導任何.NET對象,*從未*使用注射值到JavaScript代碼,除了最瑣碎的信息。它繞過了單獨的JS文件(捆綁,緩存,TypeScript等)的所有優點。相反,只需將值注入DOM(例如'data-'attributes)或者最糟糕的情況下,只需爲腳本添加幾個全局變量即可。 –

+0

知道任何地方,特別是我可以閱讀和了解這一點? @goneCoding –

+0

只是傳授經驗。經過多年的努力學習了很多你不應該做的事情,因爲他們讓維護變得更難:) –

回答

3

是的,你可以在<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> 
} 
+0

哦,爲什麼我不試試呢哈哈?好吧,謝謝! –

相關問題