chobo
chobo

Reputation: 32311

How to pass a multidimension array to javascript from c#?

I am using a JQuery charting plugin that takes in data points using a multi-dimension array

    var line1 = [['23-May-2008', 1578.55], ['20-Jun-2008', 566.5], 
['25-Jul-2008', 480.88], ['22-Aug-2008', 509.84]];

How can I return data formatted like the above from c#? I have tried generating a string that matches the output, but it doesn't work...

StringBuilder sb = new StringBuilder();

        foreach (Stats s in perfData)
        {          
            sb.Append("['" + String.Format("{0:MM-dd-yyyy}", p.Date) + "'], " + "[" + p.Value +"],");
        }

        string data = sb.ToString();
        data += data.TrimEnd(new[] { ',' });
        data = "[" + data + "]";

Upvotes: 0

Views: 2495

Answers (4)

dillenmeister
dillenmeister

Reputation: 1647

Using the JavaScriptSerializer from the System.Web.Extensions assembly:

        var data = perfData.Select(p => 
            new object[] { String.Format("{0:MM-dd-yyyy}", p.Date), p.Value });

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(data);

Upvotes: 3

L.B
L.B

Reputation: 116168

You can use any JSON serializer(DataContractJsonSerializer , JavaScriptSerializer) to convert your object to javascript format. But I , personally, prefer Json.Net.

List<object[]> array2D = new List<object[]>() { 
    new object[] { DateTime.Now.AddDays(-1000), 1578.55 }, 
    new object[] { DateTime.Now.AddDays(-2000), 566.5 },
    new object[] { DateTime.Now.AddDays(-3000), 480.88 },
    new object[] { DateTime.Now.AddDays(-4000), 509.84 } 
};

string jsonstr =  JsonConvert.SerializeObject(array2D,new MyDateTimeConvertor());


public class MyDateTimeConvertor : Newtonsoft.Json.Converters.DateTimeConverterBase
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new Exception("Not implemented yet");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((DateTime)value).ToString(@"dd-MMM-yyy"));
    }
}

and output is a valid javascript object

[["04-May-2009",1578.55],["08-Aug-2006",566.5],["12-Nov-2003",480.88],["15-Feb-2001",509.84]]

Upvotes: 4

Kshitij Banerjee
Kshitij Banerjee

Reputation: 1748

  1. shouldnt it be like below to generate what you need?
  2. This is not valid JSON, so do check if your plugin is taking JSON or not, if yes then make use of JSONserializer in C#.

    foreach (Stats s in perfData)
    {          
        sb.Append("['" + String.Format("{0:MM-dd-yyyy}", p.Date) +","+  p.Value +"],");
    }
    
    string data = sb.ToString();
    data += data.TrimEnd(new[] { ',' });
    data = "[" + data + "]";
    

Upvotes: 0

Thordax
Thordax

Reputation: 1733

I think you should try JSON helper (JavaScript Object Notation) to do that kind of manipulation. I found that link, hope this helps http://weblogs.asp.net/hajan/archive/2010/07/23/javascriptserializer-dictionary-to-json-serialization-and-deserialization.aspx

Upvotes: 0

Related Questions