mahdis dezfouli
mahdis dezfouli

Reputation: 173

How to pass array from controller to javascript?

I want to pass array (2 dimension) from controller to javascript variable. I use session to pass but this not work. In javascript code I use like this:

 var data = '<%= Session["LatLon"] %>';

when run project and use inspect element, there is in data :

enter image description here

how to pass? Can i Pass array with 2 dim with session?

Upvotes: 2

Views: 1642

Answers (2)

Ivan Gritsenko
Ivan Gritsenko

Reputation: 4236

What you are currently observing is a result of execution .ToString method of Session["LetLon"] object.

What you intent to receive is var data = [[1, 2], [3, 4]];.

So you can simply write a correct stringification of your two-dimensional array. I suggest to write simple extension method:

public static string ToJsString(this string[,] array) {
     return Enumerable.Range(0, array.GetLength(0))
            .Aggregate(new StringBuilder(),
                (sbi, i) => sbi.AppendFormat(i == 0 ? "{0}" : ", {0}",
                    Enumerable.Range(0, array.GetLength(1))
                        .Aggregate(new StringBuilder(),
                            (sbj, j) => sbj.AppendFormat(j == 0 ? "{0}" : ", {0}", array[i,j]),
                            sbj => string.Format("[{0}]", sbj))), 
                sb => string.Format("[{0}]", sb));
}

In order to use it write then var data = <%= ((string[,])Session["LatLon"]).ToJsString() %>.

Upvotes: 0

Gerard Sexton
Gerard Sexton

Reputation: 3200

When inserting the value into Session["LatLon"], save it as JSON instead of a C# string array.

string[][] mystringarr = ...
Session["LatLon"] = JsonConvert.SerializeObject(mystringarr);

And in the view use

var data = <%= Session["LatLon"] %>;

So it will generate something like

var data = [["1.0", "1.4"], ["4.6","4.8"]];

Using JSON.NET http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_SerializeObject.htm

Upvotes: 2

Related Questions