2

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?

2
  • var data = @Html.Raw(Json.Encode(Session.["LatLon"]))'; (and you may need to cast the Session value), but I strongly recommend you pass a model to the view Commented Mar 16, 2016 at 7:01
  • @StephenMuecke Thanks for help Commented Mar 16, 2016 at 7:08

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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() %>.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.