Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass C# ASP.NET array to Javascript array

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?

like image 497
locoboy Avatar asked Aug 12 '10 03:08

locoboy


People also ask

What is pass in C?

Pass by Value, means that a copy of the data is made and stored by way of the name of the parameter. Any changes to the parameter have NO affect on data in the calling function.

Does C++ have pass?

In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables.

What's pass in Python?

Python pass Statement The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function definitions, class definitions, or in if statements.

What will happen if the pass keyword isn't used for an empty class?

It can't be empty. In this if statement, removing the pass statement would keep the functionality the same and make your code shorter.


4 Answers

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) %>; 
like image 72
zerkms Avatar answered Sep 29 '22 18:09

zerkms


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.

like image 34
Anh-Kiet Ngo Avatar answered Sep 29 '22 18:09

Anh-Kiet Ngo


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.

like image 43
Gary Avatar answered Sep 29 '22 18:09

Gary


In the page file:

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

while in code behind:

public int[] numbers = WhatEverGetTheArray();
like image 37
Cheng Chen Avatar answered Sep 29 '22 19:09

Cheng Chen