最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

C# array to javascript array - Stack Overflow

programmeradmin2浏览0评论

I have two method in my code behind one returns an int array and the other returns string array. I want to use these two array to populate the google chart data table.

I do not have any experience with Json or AJAX however I found a relatively simple solution using the string.Join and eval to convert the string to an array.

I have managed to do this with the int array however I found a problem with the string array. I know that the problem is that I need to add '' to each element in the array.

function drawChart() {

    var locality = ['Loc_A', 'Loc_B', 'Loc_C', 'Loc_D', 'Loc_E'];
    //var locality =  eval('[<% =string.Join(", ", locations)%>]');
    var frequency = eval('[<% =string.Join(", ", numbers ) %>]'); 

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'locality');
    data.addColumn('number', 'frequency');

    for (i = 0; i < locality.length; i++)
        data.addRow([locality[i], frequency[i]]);

    var options = {
         title: 'Test'
     };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
}

I need to adjust the mented line by adding '' with each word so that then I can convert the string to a javascript array.

Any ideas or any other hints howto convert c# arrays from code behing to java script arrays. Code examples would be very helpful please.

I have two method in my code behind one returns an int array and the other returns string array. I want to use these two array to populate the google chart data table.

I do not have any experience with Json or AJAX however I found a relatively simple solution using the string.Join and eval to convert the string to an array.

I have managed to do this with the int array however I found a problem with the string array. I know that the problem is that I need to add '' to each element in the array.

function drawChart() {

    var locality = ['Loc_A', 'Loc_B', 'Loc_C', 'Loc_D', 'Loc_E'];
    //var locality =  eval('[<% =string.Join(", ", locations)%>]');
    var frequency = eval('[<% =string.Join(", ", numbers ) %>]'); 

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'locality');
    data.addColumn('number', 'frequency');

    for (i = 0; i < locality.length; i++)
        data.addRow([locality[i], frequency[i]]);

    var options = {
         title: 'Test'
     };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
}

I need to adjust the mented line by adding '' with each word so that then I can convert the string to a javascript array.

Any ideas or any other hints howto convert c# arrays from code behing to java script arrays. Code examples would be very helpful please.

Share Improve this question asked Nov 8, 2014 at 16:54 user2307236user2307236 7555 gold badges19 silver badges46 bronze badges 5
  • not sure if I am following you but could you now use a var options = new List<T> { "Test"}; for example and if you want to populate the List<T> you can implement the List<T>.Add() Method.. your var options would be a good example of C# List<T> – MethodMan Commented Nov 8, 2014 at 17:00
  • 1 Just use System.Web.Script.Serialization.JavaScriptSerializer to serialize .NET objects to JSON. And use JSON.parse() instead of eval. – Dmitry Commented Nov 8, 2014 at 17:02
  • What you want to do is to convert your C# data to JSON. I don't know C#, but I assume there are functions to convert various C# sources to JSON for you. Perhaps this will help: msdn.microsoft./en-us/library/bb412179(VS.100).aspx – jfriend00 Commented Nov 8, 2014 at 17:03
  • Unfortunately I have never used Json and I would need a code example with explanation to understand. – user2307236 Commented Nov 8, 2014 at 17:25
  • 3 do a google search and start to learn / understand what JSON is .. it's not that difficult.. I have never used is not a valid excuse by the way.. try to expand your horizons respectfully speaking – MethodMan Commented Nov 8, 2014 at 17:35
Add a ment  | 

2 Answers 2

Reset to default 3

METHOD 1: Chart data formatiing in drawChart()

using System.Web.Script.Serialization;

1) Build jsonobj

public string GetLocality()
    {
        string[] locality = new string[] { "Loc_A", "Loc_B", "Loc_C", "Loc_D", };
        //long[] frequency = new long[] { 10, 20, 10, 80 };
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        string jsonobj = jsSerializer.Serialize(locality);
        return jsonobj;       
    }

2) Either Add this in HTML data-attribute or pull using ajax call.

   <div id="piechart" data-piechart-localityary='<ServerSide call/var Getlocality()'> 
   <div>

3) pull in data in your javascript from html data-dash as

var locality = $('#piechart').data('piechart-localityary');

Method 2: Chart data formatting in code behind

I would remend to keep DrawChart() function simple. You mentioned you have the Arrays available in code behind.

1) Build the JavaScript string literal object in code behind. Format
2) Either attached jSonData into html page as data-attribute or pull it using ajax. I'll remend saving a server round-trip if not crucial.
3) Get this data into drawChart() from html-data-dash
4) Working example JSFIDDLE with source code

function drawChart() {

//var jsonData = $('#piechart').data('piechar-jsonobj');
var jsonData =  
{
"cols":[
    {"label":"Locality","type":"string"},
    {"label":"Frequency","type":"number"}
       ],
"rows":[
    {"c":[{"v":"Loc_A","f":null},{"v":10.00,"f":null}]},
    {"c":[{"v":"Loc_B","f":null},{"v":20.00,"f":null}]},
    {"c":[{"v":"Loc_C","f":null},{"v":10.00,"f":null}]},
    {"c":[{"v":"Loc_D","f":null},{"v":80.00,"f":null}]}
       ]
} ;

var data = new google.visualization.DataTable(jsonData);


var options = {
    title: 'MyPieChart',
    backgroundColor: { fill: 'transparent' },
    is3D: true
};

var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
} 
google.load("visualization", "1", {packages:["corechart"]}); 
google.setOnLoadCallback(drawChart);

Code to build JavaScript string literal object

 public class Graph
{
    public List<ColInfo> cols { get; set; }
    public List<DataPointSet> rows { get; set; }    
}

public class ColInfo
{

    public string label { get; set; }
    public string type { get; set; }
}

public class DataPointSet
{
    public List<DataPoint> c { get; set; }
}

public class DataPoint
{
    public string v { get; set; } // value    
    public string f { get; set; } // format
}

public string DemoPieChart()
    {
        Graph ChartData = new Graph();
        ChartData.cols = new List<ColInfo>();
        ChartData.rows = new List<DataPointSet>();
        ColInfo Col1 = new ColInfo();
        Col1.label = "Locality";
        Col1.type = "string";
        ColInfo Col2 = new ColInfo();
        Col2.label = "Frequency";
        Col2.type = "number";
        ChartData.cols.Add(Col1);
        ChartData.cols.Add(Col2);

        //Loop your data entry from both array
        string[] locality = new string[] { "Loc_A", "Loc_B", "Loc_C", "Loc_D", };
        long[] frequency = new long[] { 10, 20, 10, 80 };

        for (int i = 0; i < locality.Length; i++)
        {
            DataPointSet Row = new DataPointSet();
            Row.c = new List<DataPoint>();
            DataPoint p1 = new DataPoint();
            p1.v = locality[i];
            p1.f = null;

            DataPoint p2 = new DataPoint();
            p2.v =  frequency[i].ToString("F")  ;           
            p2.f = null;
            Row.c.Add(p1);
            Row.c.Add(p2);
            ChartData.rows.Add(Row);          
        }
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        string jsonobj = jsSerializer.Serialize(ChartData);           
        return jsonobj;
      }

Hope this helps you build your solution. In case you need clarification or specific code add ments. I build html using razor (MVC) to populate data-attributes.


Possible issue: JavaScriptSerializer adds quote around numbers.

{"c":[{"v":"Loc_A","f":null},{"v": "10.00" ,"f":null}]}

Notice "10.00" instead of 10.00. GoogleCharts doesn't like it. It might not draw chart or draw a incorrect chart.

This should do it:

    using System.Web.Script.Serialization;

    public static string SerializeListAsJsonData<T>(List<T> list)
    {
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer()
        {
            //MaxJsonLength = _maxJsonLength, <-- This is optional (used for large lists)
        };

        return jsSerializer.Serialize(list);
    }

The method takes a List of objects and serializes a JSON string for you. This string you can do a JSON.parse() on, then you can freely access the objects in JavaScript. You specifically requested something for C# arrays, but I remend sticking to lists (if you need a string array then just make a List of strings).

List<string> list = new List<string>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");

string jsonString = SerializeListAsJsonData(list); // <-- jsonString is what you send to your JavaScript.

Or like this if you somehow need to keep your string array:

 string[] stringArray = { "A", "B", "C", "D", "E" };
 string jsonString = SerializeListAsJsonData(stringArray.ToList<string>()); // <-- jsonString is what you send to your JavaScript
发布评论

评论列表(0)

  1. 暂无评论