I want to pass array (2 dimension) from controller to javascript variable. I use session to pass but this not work. In javascript code I use like this:
var data = '<%= Session["LatLon"] %>';
when run project and use inspect element, there is in data :
how to pass? Can i Pass array with 2 dim with session?
When inserting the value into Session["LatLon"], save it as JSON instead of a C# string array.
string[][] mystringarr = ...
Session["LatLon"] = JsonConvert.SerializeObject(mystringarr);
And in the view use
var data = <%= Session["LatLon"] %>;
So it will generate something like
var data = [["1.0", "1.4"], ["4.6","4.8"]];
Using JSON.NET
http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_SerializeObject.htm
What you are currently observing is a result of execution .ToString method of Session["LetLon"] object.
What you intent to receive is var data = [[1, 2], [3, 4]];.
So you can simply write a correct stringification of your two-dimensional array. I suggest to write simple extension method:
public static string ToJsString(this string[,] array) {
return Enumerable.Range(0, array.GetLength(0))
.Aggregate(new StringBuilder(),
(sbi, i) => sbi.AppendFormat(i == 0 ? "{0}" : ", {0}",
Enumerable.Range(0, array.GetLength(1))
.Aggregate(new StringBuilder(),
(sbj, j) => sbj.AppendFormat(j == 0 ? "{0}" : ", {0}", array[i,j]),
sbj => string.Format("[{0}]", sbj))),
sb => string.Format("[{0}]", sb));
}
In order to use it write then var data = <%= ((string[,])Session["LatLon"]).ToJsString() %>.
Related
I have JS function like this inside the #section Scripts of .cshtml view:
function SendIndexes() {
var selectedSortOption = $("#SortBy").find('option:selected');
var sortIndex = selectedSortOption.val();
var selectedFilterByTypeOption = $("#filter_marker_bytype").find('option:selected');
var filterByTypeIndex = selectedFilterByTypeOption.val();
var selectedFilterByScoreOption = $("#filter_marker_byscore").find('option:selected');
var filterByScoreIndex = selectedFilterByScoreOption.val();
var selectedFilterByStatusOption = $("#filter_marker_bystatus").find('option:selected');
var filterByStatusIndex = selectedFilterByStatusOption.val();
var markerFilterIndexes = [filterByTypeIndex, filterByScoreIndex, filterByStatusIndex];
location.href = `/Markers/MarkersList?page=#Model.PagingInfo.CurrentPage&sortIndex=${sortIndex}&markerFilterIndexes=${markerFilterIndexes}`
}
and the controller action signature like this:
public async Task<IActionResult> MarkersList(List<string> markersForUpdateIds, IEnumerable<int> markerFilterIndexes, int page = 1, string message = "", int sortIndex = 0)
{
...
}
The problem is that the array of three elements is not passed at all. However, if I only push a single variable (element) to this array, then it is passed to the controller's action as it should.
Why is this happening and how to have all three elements passed to the controller?
I'll suggest you to use [FromQuery] attribute in your parameter and format your URL like this: myparam=myvalue1&myparam=value2&myparam=myvalue3.
public async Task<IActionResult> MarkersList([FromQuery]List<string> markersForUpdateIds, [FromQuery]IEnumerable<int> markerFilterIndexes, [FromQuery]int page = 1,[FromQuery] [FromQuery]string message = "", [FromQuery]int sortIndex = 0)
{
...
}
Take a look of ModelBinding:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1#sources
For passing an array to the controller action. Data formats that use subscript numbers (... [0] ... [1] ...) must ensure that they are numbered sequentially starting at zero. Here you don't need to define an array, just format your url like this:
location.href = `/Markers/MarkersList?page=#Model.PagingInfo.CurrentPage&sortIndex=${sortIndex}&markerFilterIndexes[0]=${filterByTypeIndex}&markerFilterIndexes[1]=${filterByScoreIndex}&markerFilterIndexes[2]=${filterByStatusIndex}`
Since the data in the array is just int type data, you can omit the subscript numbers.
I need to pass a matrix from the C# code behind to javascript, however at the moment when my matrix is passed to the view, it is converted into a single dimensional array. In other words, my multi dimensional array is flattened by the serialization.
C# code
List<leituras> listaleituras = new List<leituras>();
public object[,] arrayTemperatura = new object[5, 3];
public JavaScriptSerializer javaSerial = new JavaScriptSerializer();
foreach (var leitura in listaleituras)
{
arrayTemperatura[i, 0] = leitura.Data.Month.ToString() + "/" + leitura.Data.Year.ToString();
arrayTemperatura[i, 1] = leitura.Sensor_temperatura;
arrayTemperatura[i, 2] = leitura.Sensor_temperatura;
i++;
}
Output
expected output format
[
["09/18",95,95],["10/18",257,257],["11/18",1368,1368],["12/18",1574,1574],
["01/19",2437,2437],["02/19",3105,3105],["1/3",2096,2096],["2/3",1098,1098],
["4/3",361,361],["6/3",1993,1993],["7/3",2744,2744],["8/3",2891,2891],
["9/3",1797,1797],["11/3",3027,3027],["12/3",2996,2996],["13/3",2766,2766],
["14/3",3067,3067],["15/3",3043,3043],["16/3",2374,2374]
]
How do I pass a serialized multi dimensional array?
use JSON.NET
string json_string = JsonConvert.SerializeObject(arrayTemperatura);
it serializes multi-dimension arrays as you want.
then in javascript you can desrialize json using JSON.parse
var multidimentionArray = JSON.parse( json_string );
also see this
Use a jagged array instead of a two-dimensional array.
First of all declare your array without intialising it: public object[][] arrayTemperatura;
then do this after your while loop:
arrayTemperatura = new object[listaleituras.length][];
foreach (var leitura in listaleituras)
{
arrayTemperatura[i] = new object[3];
arrayTemperatura[i][0] = leitura.Data.Month.ToString() + "/"+ leitura.Data.Year.ToString();
arrayTemperatura[i][1] = leitura.Sensor_temperatura;
arrayTemperatura[i][2] = leitura.Sensor_temperatura;
i++;
}
Alternatively you could use the Json.NET serializer instead of the JavaScriptSerializer - I have created an example to show that it just behaves the way you'd expect in your question: https://dotnetfiddle.net/2QBP7J
I would like to know how I can get the javascript values of a C # Session variable that contains an array of strings. The code is as follows: C #:
if (Session["PolizasClientes_RowID"] != null)
{
Session.Remove("PolizasClientes_RowID");
}
var array = lstPolizas.Where(x => x.POLIZA == row_id).Select(x => x.DNI).ToArray();
var array2 = lstPolizas.Where(x => x.POLIZA == row_id).Select(x => x.POLIZA).ToArray();
string dni= array[0];
string poliza = array2[0];
string[] arrays = new string[] { dni, poliza };
Session["PolizasClientes_RowID"] = arrays;
javascript::
var valores_sesion = '<%=Session["PolizasClientes_RowID"]%>';
//return System.string[] :
console.log(valores_sesion);
//return S
console.log(valores_sesion[0]);
//reurn S
console.log(valores_sesion[0][0]);
You need to use some JSON framework like Newtonsoft Json.NET, for instance. Install it using NuGet and then serialize your array into JSON like this:
var valores_sesion = <%=JsonConvert.SerializeObject(Session["PolizasClientes_RowID"])%>;
var valores_sesion = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Session("PolizasClientes_RowID")) %>;
try this
I am at a point where I can pull a single javascript declaration such as:
var cars = ["Saab", "Volvo", "BMW"];
parsed from a page.
I would like to be able to get all the elements of the array ("Saab", "Volvo", "BMW") from this declaration.
Should I be using some javascript engine for this, or what else would be the best way to get javascript variable values from my Java code.
I would hate to reinvent the wheel if something is already out there that is able to do this, so I am just looking for advice on something I can use to do this function.
I assume you found a way to transport that javascript object/array into your Java domain as a String or Stream. What you want now is a JSON parser.
One way is to use json.org or other libraries. Further information about json parsing can be found in this thread:
How to parse JSON in Java
The [org.json][1] library is easy to use. Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
} You may find extra examples from: [Parse JSON in Java][2]
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
[1]: http://www.json.org/java/index.html
[2]: http://theoryapp.com/parse-json-in-java/
You might also want to look into jsonb (https://jcp.org/en/jsr/detail?id=353) that was introduced with Java 7. You can bind an object model and transform JSON objects into java objects and vice versa.
you can iterate through all the values in 'window'
for ( var key in window )
{
if ( typeof window]key] == 'object' && window]key].length > 0 )
{
//this is the array you are looking for
}
}
You can get access to javascript object from java by using httpunit
Method 1: JSON parser, as Alex's answer.
Method 2: Javascript parser for Java
Method 3: Regular Expression (A weird way I figured out!)
First pattern is var\s+([a-zA-Z0-9]+)\s+=\s+\[(.*)\]\s*;*
var + one or more space(s) + variable name($1) + one or more space(s) + equals sign + one or more space(s) + array content($2) + ......
Second pattern is "(.*?)", get the string between two quotation marks.
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JSParser {
public String arrayName;
private String tempValues;
public ArrayList<String> values = new ArrayList<String>();
public boolean parseJSArray(String arrayStr){
String p1 = "var\\s+([a-zA-Z0-9]+)\\s+=\\s+\\[(.*)\\]\\s*;*";
Pattern pattern1 = Pattern.compile(p1);
Matcher matcher = pattern1.matcher(arrayStr);
if(matcher.find()){
arrayName = matcher.group(1);
tempValues = matcher.group(2);
Pattern getVal = Pattern.compile("\"(.*?)\"");
Matcher valMatcher = getVal.matcher(tempValues);
while (valMatcher.find()) { // find next match
String value = valMatcher.group(1);
values.add(value);
}
return true;
}else{
return false;
}
}
}
With JDK 8 the code bellow works :
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String js = "var carsfromjs = [\"Saab\", \"Volvo\", \"BMW\"]";
engine.eval(js);
String[] cars = (String[])engine.eval("Java.to(carsfromjs, \"java.lang.String[]\")");
for(int i=0; i<cars.length; i++){
System.out.println(cars[i]);
}
You can find many ways to access Javascript code throught "nashorn" :
http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/
In Rails, I am querying the database to build a data object for highcharts.
Here is my method from my controller:
def build_data_for_chart
data_array = Array.new
#data_array_as_json = ''
#issues.each {
|issue|
# returns an array of KeyIssue objects for a given issue
given_issue_array = KeyIssues.where(issue: issue).all
a = Array.new
#loop through each element extracting the timedate and % and add to new array
given_issue_array.each {
|entry|
a.push([entry.datetime.utc.to_date, entry.percentage])
}
#build the hash for an individual issue
temp_hash = {:name => issue, :data => a, :animation => false}
#add the individual issue and all its data to a final array that contains all the issues.
data_array.push(temp_hash)
}
#data_array_as_json = data_array.to_json.html_safe
end
Now I am trying to pull it out in a script in my view.
--- script ---
var data = $.parseJSON(<%= #data_array_as_json %>);
--- script ---
When I print to console, I can see the objects and all their data. Also when I print to html the output looks correct:
"[{\"name\":\"ABORIGINAL & NATIVE TITLE ISSUES\",\"data\":[[\"1993-11-01\",32],[\"1994-06-01\",27],[\"1994-09-01\",33],[\"1995-06-01\",26],[\"1995-09-01\",24],[\"1996-01-01\",20],[\"1996-09-01\",27],[\"1997-01-01\",33],[\"1997-06-01\",36],[\"1997-09-01\",36],[\"1998-01-01\",37],[\"1998-05-01\",33],[\"1998-09-01\",31],[\"1999-05-01\",30],[\"1999-09-01\",28],[\"2000-01-01\",30],[\"2000-05-01\",31],[\"2000-09-01\",34],[\"2001-01-01\",32],[\"2001-06-01\",29],[\"2001-09-01\",28],[\"2002-02-01\",25],[\"2002-06-01\",27],[\"2002-10-01\",25],[\"2003-02-01\",24],[\"2003-06-01\",26],[\"2003-10-01\",27],[\"2004-02-01\",27],[\"2004-06-01\",26],[\"2005-06-01\",30],[\"2006-06-01\",27],[\"2007-06-01\",31],[\"2008-07-01\",29]],\"animation\":false}]"
But when I go to print the data variable it is null (obviously due to not being valid input). What am I messing up?
FYI..
I needed to wrap it in single quotes.. to make it work..
$.parseJSON(' <%= #data_array_as_json %> ');
You can try this:
<script type="text/javascript">
var data = <%== data_array.to_json %>
</script>