views:

376

answers:

4

Does anyone know how to pass a C# ASP.NET array to a Javascript array? Sample code will also be nice.

Sorry if I was vague earlier guys. The question is actually quite simple. Let's say for simplicity that in my aspx.cs file I declare:

int [] numbers = new int[5];

now I want to pass "numbers" to the client side and use the data in the array within javascript. How would I do this?

A: 

serialize it with System.Web.Script.Serialization.JavaScriptSerializer class and assign to javascript var

dummy sample:

<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
var jsVariable = <%= serializer.Serialize(array) %>;
zerkms
I often find it helpful to diagnose *before* prescribing.
Steven Sudit
@Steven Sudit: ?
zerkms
@zerkms: he is saying that it's better to wait for the OP to explain before taking shots in the dark at the solution to a VERY ambiguous question.
samandmoore
sorry for the ambiguity. please see above.
cfarm54
@cfarm54: so? what's wrong with my answer?
zerkms
@zerkms could you explain what's going on? sorry i'm noob at this
cfarm54
@samandmoore: Yes, that's precisely what I was saying.
Steven Sudit
@Steven Sudit: it is not my problem that he knows nothing about asp.net. my answer is suitable for his question. btw, you did not answer anything but criticize. try to teach him from scratch here and good luck ;-)
zerkms
@zerkms: Two people were asking the OP to clarify, so you just went ahead and posted a guess. Think about it for a moment and you'll see why we're not particularly impressed.
Steven Sudit
@Steven Sudit: and i am still right, because the most suitable case to pass the list/array to js is to serialize it to json.
zerkms
@zerkms: Since I had already asked whether they were trying to find out about JSON serialization, it seems odd that you take credit for figuring out what the OP wanted. Whereas samandmoore and I were willing to ask for clarification and wait for an answer, you took *my* answer and wrote it up. This did not add value.
Steven Sudit
+2  A: 

In the page file:

<script type="text/javascript">
    var a = eval('[<% =string.Join(", ", numbers) %>]');
</script>

while in code behind:

public int[] numbers = WhatEverGetTheArray();
Danny Chen
I'm not sure I understand the answer here...can you walk me through it?
cfarm54
@cfarm54-In code behind, you initialize the int[] called numbers. And then in the javascript, `string.Join(", ", numbers)` make the "numbers" array to be a string like "1,2,3,4". After that, we use `eval('[1,2,3,4]')` to convert an array-like string to an array.
Danny Chen
ahhh tricky. however what is the type of the js array?
cfarm54
The variable "a" will be the exact js array. You can use any array operation to it e.g. a[0] a[1] a.length.
Danny Chen
+2  A: 

You can use ClientScript.RegisterStartUpScript to inject javascript into the page on Page_Load.

Here's a link to MSDN reference: http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Here's the code in Page_Load:

  List<string> tempString = new List<string>();
  tempString.Add("Hello");
  tempString.Add("World");

  StringBuilder sb = new StringBuilder();
  sb.Append("<script>");
  sb.Append("var testArray = new Array;");
  foreach(string str in tempString)
  {
    sb.Append("testArray.push('" + str + "');");
  }
  sb.Append("</script>");

  ClientScript.RegisterStartupScript(this.GetType(), "TestArrayScript", sb.ToString());

Notes: Use StringBuilder to build the script string as it will probably be long.

And here's the Javascript that checks for the injected array "testArray" before you can work with it:

if (testArray)
{
  // do something with testArray
}

There's 2 problems here:

  1. Some consider this intrusive for C# to inject Javascript

  2. We'll have to declare the array at a global context

If you can't live with that, another way would be to have the C# code save the Array into View State, then have the JavaScript use PageMethods (or web services) to call back to the server to get that View State object as an array. But I think that may be overkill for something like this.

Gary
I'll take a look thanks for the explanation. One thing, which array are you referring to as global and why?
cfarm54
also can you point out what this.GetType() is referring to?
cfarm54
@Gary: My concern here is the ad hoc serialization. If the strings in that list were to contain single quotes, we'd have a problem. That's why using the JSON serializer is safer.
Steven Sudit
@cfarm54: The "this" is the `Page`. Using `RegisterStartupScript` is a good idea.
Steven Sudit
@cfarm54: If you look at where we have to declare the testArray array, it is a global variable in Javascript.And yes, "this" refers to the Page in this case. If you put this in a User Control, it will return the User Control type; registering the code to the control rather than the page.
Gary
@Steven: That is true. I think this solution is a "quick fix" and it is good enough as the scope of object that we're passing is small. If we were to pass bigger objects then JSON serialization would be the way to go.
Gary
thanks guys that makes a lot of sense. the actual problem is that I'm calling a webservice in the .cs file which returns an array of doubles. If I then push this into javascript (where I can use a nice google scatter plot), would this interfere with the other components on the page if I was using js for those also? I'm assuming that it'd only affect it if I were to declare another js array with the same name...
cfarm54
@cfarm54: It should not affect other scripts. It's equivalent of having multiple <script> sections or multiple .js files on your page. If you do call RegisterClientScript multiple times, please ensure that the second parameter ("TestArrayScript" in this case) is unique to the other RegisterClientScript's.If my answer is helpful, please rate up / mark answer! I'm trying to get enough points to put comments :) Thanks!
Gary
Yes you are helping a lot. I'm also new to stack overflow, how do I rate up?
cfarm54
@Gary: My concern here is correctness, not size. Since the OP is using doubles and converting them, there doesn't seem to be any risk of injection, however.
Steven Sudit
+2  A: 

This is to supplement zerkms's answer.

To pass data across language barriers, you would need a way to represent the data as a string by serializing the data. One of the serialization methods for JavaScript is JSON. In zerkms's example, the code would be placed inside of an aspx page. To combine his example and yours together on one aspx page, you would have,

<%
    int[] numbers = new int[5];
    // Fill up numbers...

    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
%>

somewhere later on the aspx page

<script type="text/javascript">
    var jsVariable = <%= serializer.Serialize(numbers) %>;
</script>

This answer though, assumes that you are generating JavaScript from the initial page load. As per the comments in your post, this could have been done via AJAX. In that case, you would have the server respond with the result of the serialization and then deserialize it in JavaScript using your favorite framework.

Note: Also do not mark this as an answer since I wanted the syntax highlighting to make another answer more clear.

Anh-Kiet Ngo
do you mean:var jsVariable = <%=serializer.Serialize(numbers)%>?
cfarm54
also, what do you mean generatign js from the initial page load?
cfarm54
No, because you are in the context of generating JavaScript. When you have int[] numbers = new int[5] { 1, 3, 5, 7, 9 }, serializing it gives you, "[1, 3, 5, 7, 9]". So the generated javascript becomes "var jsVariable = [1, 3, 5, 7, 9];"
Anh-Kiet Ngo
Correction, you are right, serializer.Serialize(numbers) with the semicolon. I misread and thought you meant the semicolon. I've also made the correction to the code.
Anh-Kiet Ngo
cool thanks for the help
cfarm54
for some reason this isn't working. int[] is on the backend (aspx.cs file) and I also declare the serializer in the cs file. when i write out the script tag I get the error that int[] doesn't exist within the current context
cfarm54