简体   繁体   English

使用Razor C#将对象动态添加到javascript数组

[英]Dynamically add objects to javascript array with Razor C#

Okay so I'm working with MVC4 in C# and I have to fill a javascript array with elements from the view's model. 好的,所以我正在C#中使用MVC4,我必须用视图模型中的元素填充javascript数组。 I'm trying to dynamically populate a Chart.js pie chart. 我正在尝试动态填充Chart.js饼图。 This is my example code: 这是我的示例代码:

<script src="~/Scripts/Chart.js"></script>
<script type="text/javascript">

    var data = [
        {
            value: 30,
            color: "#F38630"
        },
        {
            value: 50,
            color: "#E0E4CC"
        },
        {
            value: 100,
            color: "#69D2E7"
        }
        ]
    //Get the context of the canvas element we want to select
    var ctx = document.getElementById("myChart").getContext("2d");
    var myNewChart = new Chart(ctx).Pie(data);
    //Get context with jQuery - using jQuery's .get() method.
    var ctx = $("#myChart").get(0).getContext("2d");
    //This will get the first returned node in the jQuery collection.
    var myNewChart = new Chart(ctx);
    new Chart(ctx).Pie(data, options);
</script>

I want to be able to add elements to the data array in a for loop. 我希望能够在for循环中向数据数组添加元素。 I tried using .push like this 我尝试像这样使用.push

data.push([{ value: 30, color: "#F38630" }]); data.push([{value:30,color:“#F38630”}]));

But it stops the chart from being created entirely. 但这使图表无法完全创建。 Any idea how I can do something like: 任何想法,我怎么可以做这样的事情:

foreach (var item in Model.List) {

data.add(item.value)

}

You can be even more awesome than that. 您可以做到的比这还棒。

Create your own basic type to represent you Value/Color pair. 创建您自己的基本类型以表示“值/颜色”对。

public class MyType 
{
    public string Value {get;set;}
    public string Color {get;set;}
}

In your razor (or code behind) create an array for that type: 在剃刀(或后面的代码)中,为该类型创建一个数组:

@{
    var values = new List<MyType>();
    // populate with some values.

    JavaScriptSerializer js = new JavaScriptSerializer();
    string json = js.Serialize(keyValues.ToArray());
}

Then in your Javascript: 然后在您的Javascript中:

<script type="text/javascript">

    var data = @json; // TADA!!

    //Get the context of the canvas element we want to select
    var ctx = document.getElementById("myChart").getContext("2d");
    var myNewChart = new Chart(ctx).Pie(data);

    //... etc.

</script>

If you come across any problems serializing that list, I recommend using Json.Net to improve C# native serializers. 如果您在序列化该列表时遇到任何问题,建议您使用Json.Net来改进C#本机序列化程序。

Your data is an array (see the brackets [] ). 您的data是一个数组(请参见方括号[] )。

Now you try to add an array with a single object to the array: 现在,您尝试将具有单个对象的数组添加到该数组:

[{ value...

Just change it to an object {} and you will be fine. 只需将其更改为对象{} ,就可以了。

{ value ... }

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

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