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?
This question is related to
c#
javascript
asp.net
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)');
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.
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.
In the page file:
<script type="text/javascript">
var a = eval('[<% =string.Join(", ", numbers) %>]');
</script>
while in code behind:
public int[] numbers = WhatEverGetTheArray();
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)
})))
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) %>;
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.
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.
Source: Stackoverflow.com