Pass C# ASP.NET array to Javascript array
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.
Pass Array to Javascript Array C# ASP.NET
Try creating a property named "_Result" for that:
In code behind:
//Add this line
public String _Result {get;set;}
protected void Page_Load(object sender, EventArgs e)
{
//Set the course object here
ArrayList Course = new ArrayList();
const string connectionString = "Data Source=localhost;" + "Initial Catalog=IBBTS_DB; Integrated Security =SSPI";
const string query = "SELECT X from accelerometerReading";
using (SqlConnection cn = new SqlConnection(connectionString))
{
using (SqlCommand cm = new SqlCommand(query, cn))
{
cn.Open();
SqlDataReader reader = cm.ExecuteReader();
while (reader.Read())
{
Course.Add(reader.GetDecimal(0));
}
}
}
_Result = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Course);
}
Then in the markup page:
var javaVariable = <%= _Result %>
This error message shows because "Course" is not a global variable, so markup page is unable to access "Course" object.
c# asp.net array for corresponding js array
If you want to set the array from the code behind, you need to manually build up the array as a JavaScript string and then register your script with the ClientScript.RegisterStartupScript
.
Something like this should get you started:
List<string> totalData = new List<string>();
totalData.Add("Jan, 25");
totalData.Add("Feb, 42");
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var TotalData = new Array();");
foreach(string str in totalData)
{
sb.Append("TotalData.push('" + str + "');");
}
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "InitTotalData", sb.ToString());
InitTotalData is the script name as identified by the ClientScriptManager. You can print the contents of the JavaScript array like so:
alert(TotalData.join());
This will output:
Jan, 25,Feb, 42
If you want to embed the array directly in the ASPX page, you can do something like the following:
<script type="text/javascript">
<% var totalDataCSharp = new List<string>() { "Jan, 25", "Feb, 42" } %>
<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
var TotalData = <%= serializer.Serialize(totalDataCSharp) %>;
</script>
Note, the totalDataCSharp
list can be maintained from the code behind.
Pass C# Array To Javascript
Replace
var a = '<%= this.javaSerial.Serialize(this.names) %>';
with
var a = <%= this.javaSerial.Serialize(this.names) %>;
You were putting the resulting JSON into a javascript string, which would result in your example output iterating through each character of the Serialize
call.
C# array to javascript array
METHOD 1: Chart data formatiing in drawChart()
using System.Web.Script.Serialization;
1) Build jsonobj
public string GetLocality()
{
string[] locality = new string[] { "Loc_A", "Loc_B", "Loc_C", "Loc_D", };
//long[] frequency = new long[] { 10, 20, 10, 80 };
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonobj = jsSerializer.Serialize(locality);
return jsonobj;
}
2) Either Add this in HTML data-attribute or pull using ajax call.
<div id="piechart" data-piechart-localityary='<ServerSide call/var Getlocality()'>
<div>
3) pull in data in your javascript from html data-dash as
var locality = $('#piechart').data('piechart-localityary');
Method 2: Chart data formatting in code behind
I would recommend to keep DrawChart() function simple. You mentioned you have the Arrays available in code behind.
1) Build the JavaScript string literal object in code behind.
Format
2) Either attached jSonData into html page as data-attribute or pull it using ajax. I'll recommend saving a server round-trip if not crucial.
3) Get this data into drawChart() from html-data-dash
4) Working example JSFIDDLE with source code
function drawChart() {
//var jsonData = $('#piechart').data('piechar-jsonobj');
var jsonData =
{
"cols":[
{"label":"Locality","type":"string"},
{"label":"Frequency","type":"number"}
],
"rows":[
{"c":[{"v":"Loc_A","f":null},{"v":10.00,"f":null}]},
{"c":[{"v":"Loc_B","f":null},{"v":20.00,"f":null}]},
{"c":[{"v":"Loc_C","f":null},{"v":10.00,"f":null}]},
{"c":[{"v":"Loc_D","f":null},{"v":80.00,"f":null}]}
]
} ;
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'MyPieChart',
backgroundColor: { fill: 'transparent' },
is3D: true
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
Code to build JavaScript string literal object
public class Graph
{
public List<ColInfo> cols { get; set; }
public List<DataPointSet> rows { get; set; }
}
public class ColInfo
{
public string label { get; set; }
public string type { get; set; }
}
public class DataPointSet
{
public List<DataPoint> c { get; set; }
}
public class DataPoint
{
public string v { get; set; } // value
public string f { get; set; } // format
}
public string DemoPieChart()
{
Graph ChartData = new Graph();
ChartData.cols = new List<ColInfo>();
ChartData.rows = new List<DataPointSet>();
ColInfo Col1 = new ColInfo();
Col1.label = "Locality";
Col1.type = "string";
ColInfo Col2 = new ColInfo();
Col2.label = "Frequency";
Col2.type = "number";
ChartData.cols.Add(Col1);
ChartData.cols.Add(Col2);
//Loop your data entry from both array
string[] locality = new string[] { "Loc_A", "Loc_B", "Loc_C", "Loc_D", };
long[] frequency = new long[] { 10, 20, 10, 80 };
for (int i = 0; i < locality.Length; i++)
{
DataPointSet Row = new DataPointSet();
Row.c = new List<DataPoint>();
DataPoint p1 = new DataPoint();
p1.v = locality[i];
p1.f = null;
DataPoint p2 = new DataPoint();
p2.v = frequency[i].ToString("F") ;
p2.f = null;
Row.c.Add(p1);
Row.c.Add(p2);
ChartData.rows.Add(Row);
}
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonobj = jsSerializer.Serialize(ChartData);
return jsonobj;
}
Hope this helps you build your solution. In case you need clarification or specific code add comments. I build html using razor (MVC) to populate data-attributes.
Possible issue: JavaScriptSerializer adds quote around numbers.
{"c":[{"v":"Loc_A","f":null},{"v": "10.00" ,"f":null}]}
Notice "10.00" instead of 10.00. GoogleCharts doesn't like it. It might not draw chart or draw a incorrect chart.
Related Topics
Is There an Alternative to String.Replace That Is Case-Insensitive
Jit Compiler VS Offline Compilers
Publishing a Website Is Not Updating My CSS Bundles
Arkit Body Tracking Using Xamarin and C# Inaccurate
Why Aren't Variables Declared in "Try" in Scope in "Catch" or "Finally"
How Does MVC 4 List Model Binding Work
Data Binding in Wpf User Controls
Drag and Drop to Desktop/Explorer
How to Find Multiple Occurrences with Regex Groups
How to Get Linq to Return the Object Which Has the Max Value for a Given Property
Can't Connect to Localhost on SQL Server Express 2012/2016
What Are the Definitions for Lparam and Wparam
Asp:Fileupload Edit "No File Selected" Message
How to Call Code Behind Server Method from a Client Side JavaScript Function
Send Email Using System.Net.Mail Through Gmail
Use Linq to Group a Sequence of Numbers with No Gaps
Is There Really Any Way to Uniquely Identify Any Computer at All