user2836518
user2836518

Reputation:

How to pass a C# array to a JavaScript array

I am trying to pass my C# array to the JavaScript behind, I've managed to pass a integer to the code behind but when I try to pass the array, it only shows: var rawData = System.Int32[,];

This is what I have tried so far:

JavaScript

var rawData = <%=this.array2D%>;

C#

public int[,] array2D;

protected void Page_Load(object sender, EventArgs e)
{
    array2D = new int[,] { { 700, 0 }, { 300, 1 }, { 500, 2 }, { 700, 3 }, { 400, 4} };
}

Is what I want to achieve possible and if so, any suggestions to have I can make it work? Cheers.

Upvotes: 0

Views: 291

Answers (3)

Amir Popovich
Amir Popovich

Reputation: 29846

Using Json.Net:

string json = JsonConvert.SerializeObject(array2D);

Upvotes: 1

abj27
abj27

Reputation: 131

You can try tu use a js serializer on the view <%@ Import Namespace="System.Web.Script.Serialization" %> var rawData = <%=new JavaScriptSerializer().Serialize(this.array2D) %>

Upvotes: 0

Andrew
Andrew

Reputation: 5277

You would first need to serialize your C# object to json. You can use something like json.net to achieve this. Once on the client side in the javascript you need to parse the json to convert it into javascript. You can have a look at a javascript library like json2 to do this.

Upvotes: 0

Related Questions