Reputation: 38940
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?
Upvotes: 43
Views: 114695
Reputation: 1317
The array of integers is quite simple to pass. However this solution works for more complex data as well. In your model:
public int[] Numbers => new int[5];
In your view:
numbers = @(new HtmlString(JsonSerializer.Serialize(Model.Numbers)))
A tip for passing strings. You may want JSON encoder to not escape some symbols in your strings. In this example I want raw unescaped cyrillic letters. In your view:
strings = @(
new HtmlString(
JsonSerializer.Serialize(Model.Strings, new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.Create(
UnicodeRanges.BasicLatin,
UnicodeRanges.Cyrillic)
})))
Upvotes: 0
Reputation: 589
Here is another alternative solution. You can use ClientScriptManager Page.ClientScript.RegisterArrayDeclaration. Here is an example for chart data.
var page = HttpContext.Current.CurrentHandler as Page;
_data = "[Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]";
page.ClientScript.RegisterArrayDeclaration("chartdata0", _data);
This code creates an array on the client side
var chartdata0 = new Array([Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]);
See the following article
This solution has an issue with bigger arrays on chrome 64 browser including "Version 78.0.3904.70 (Official Build) (64-bit)". You may get "Uncaught RangeError: Maximum call stack size exceeded". However it is working with IE11, Microsoft Edge, and FireFox.
Upvotes: 0
Reputation: 313
I came up with this similar situation and I resolved it quiet easily.Here is what I did. Assuming you already have the value in array at your aspx.cs
page.
1)Put a hidden field in your aspx page and us the hidden field ID to store the array value.
HiddenField2.Value = string.Join(",", myarray);
2)Now that the hidden field has the value stored, just separated by commas. Use this hidden field in JavaScript like this. Simply create an array in JavaScript and then store the value in that array by removing the commas.
var hiddenfield2 = new Array();
hiddenfield2=document.getElementById('<%=HiddenField2.ClientID%>').value.split(',');
This should solve your problem.
Upvotes: 4
Reputation: 4492
Prepare an array (in my case it is 2d array):
// prepare a 2d array in c#
ArrayList header = new ArrayList { "Task Name", "Hours"};
ArrayList data1 = new ArrayList {"Work", 2};
ArrayList data2 = new ArrayList { "Eat", 2 };
ArrayList data3 = new ArrayList { "Sleep", 2 };
ArrayList data = new ArrayList {header, data1, data2, data3};
// convert it in json
string dataStr = JsonConvert.SerializeObject(data, Formatting.None);
// store it in viewdata/ viewbag
ViewBag.Data = new HtmlString(dataStr);
Parse it in the view.
<script>
var data = JSON.parse('@ViewBag.Data');
console.log(data);
</script>
In your case you can directly use variable name instead of ViewBag.Data.
Upvotes: 4
Reputation: 471
For array of objects:
var array= JSON.parse('@Newtonsoft.Json.JsonConvert.SerializeObject(numbers)'.replace(/"/g, "\""));
For array of int:
var array= JSON.parse('@Newtonsoft.Json.JsonConvert.SerializeObject(numbers)');
Upvotes: 9
Reputation: 2161
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.
Upvotes: 18
Reputation: 1007
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:
Some consider this intrusive for C# to inject Javascript
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.
Upvotes: 17
Reputation: 43523
In the page file:
<script type="text/javascript">
var a = eval('[<% =string.Join(", ", numbers) %>]');
</script>
while in code behind:
public int[] numbers = WhatEverGetTheArray();
Upvotes: 11
Reputation: 254926
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) %>;
Upvotes: 58