简体   繁体   中英

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. I'm trying to dynamically populate a Chart.js pie chart. 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. I tried using .push like this

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:

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

Your data is an array (see the brackets [] ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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