In viewmodel object, below is the property:
public IList<CollegeInformationDTO> CollegeInformationlist { get; set; }
In VIEW, javascript is as follow:
var obj = JSON.stringify('#Model.CollegeInformationlist');
alert(obj[1].State); //NOT WORKING, giving string char
$.each('#Model.CollegeInformationlist', function (i, item) {
var obj = JSON.stringify(item);
var r = $.parseJSON(obj);
alert(r.State); //just giving undefined.
});
Please guide here, how i can get JSON object in javascript.
You could use the following:
var json = #Html.Raw(Json.Encode(#Model.CollegeInformationlist));
This would output the following (without seeing your model I've only included one field):
<script>
var json = [{"State":"a state"}];
</script>
Working Fiddle
AspNetCore
AspNetCore uses Json.Serialize intead of Json.Encode
var json = #Html.Raw(Json.Serialize(#Model.CollegeInformationlist));
MVC 5/6
You can use Newtonsoft for this:
#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model,
Newtonsoft.Json.Formatting.Indented))
This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.
In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().
It should be as simple as:
<script>
var json = #Json.Serialize(Model.CollegeInformationlist);
</script>
After use codevar json = #Html.Raw(Json.Encode(#Model.CollegeInformationlist));
You need use JSON.parse(JSON.stringify(json));
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
#model IEnumerable<CollegeInformationDTO>
#section Scripts{
<script>
var jsArray = JSON.parse('#Html.Raw(Json.Encode(#Model))');
</script>
}
If You want make json object from yor model do like this :
foreach (var item in Persons)
{
var jsonObj=["FirstName":"#item.FirstName"]
}
Or Use Json.Net to make json from your model :
string json = JsonConvert.SerializeObject(person);
The following code worked for me
var chartD = JSON.parse(JSON.stringify([#Json.Serialize(#Model)]));
Related
I'm trying to convert an object of the following C# class type into a Javascript array of arrays:
public class SankeyData
{
public string Source { get; set; }
public int Width { get; set; }
public string Destination { get; set; }
}
The array of arrays in Javascript needs to look like this:
[["Link1",10,"Link2"],["Link3",20,"Link4"],["Link5",30,"Link6"]]
Is there an easy way to do the conversion? I'm using a jQuery $.getJSON to get the data from a C# controller action.
My related technologies include MVC5, jQuery, and JSON. I've tried using JSON.stringify and JSON.parse, but the data won't come over correctly.
Here's what I have so far:
$.getJSON('/Application/Sankey', { id: #Model.ID }, function (data) {
$.each(data, function (i, item) {
sankey.setData(JSON.stringify(item));
});
});
Which gives a close result, but not quite what I need:
[{"Source":"Link1","Width":10,"Destination":"Link2"},{"Source":"Link3","Width":20,"Destination":"Link4"},{"Source":"Link5","Width":30,"Destination":"Link6"}]
NOTE: I'm already using an MVC #model for something else in the page so I can't just set the #model to the SankeyData class.
There is no direct way out there to serialized C# objects to JSON Array. You can achieve this either
By converting C# objects to C# Array and then serialise the array as JSON.
Use Javascript to convert serialised objects to JSON Array.
I would recommend second option as array is heterogeneous.
Something like this:
function objectsToArray(data, columns) {
var dataArray = [];
for (var i in data) {
var itemArray = [];
for (var j in columns) {
itemArray.push(data[i][columns[j]]);
}
dataArray.push(itemArray);
}
return dataArray;
}
data = [{"Source":"Link1","Width":10,"Destination":"Link2"},{"Source":"Link3","Width":20,"Destination":"Link4"},{"Source":"Link5","Width":30,"Destination":"Link6"}]
console.log(objectsToArray(data, ["Source", "Width", "Destination"]));
So, just pull data using $.getJSON and the feed to objectsToArray with key names in order. Hope that solves your problem.
public String getVatNetAmount()
{
String expensetype = getRequest().getParameter("type");
String localAmount = getRequest().getParameter("amount");
Double localamt = Double.parseDouble(localAmount);
Double netAmount;
netAmount = getExpensesTypeManager().getVatNetAmount(expensetype,localAmount);
am = (float) ((localamt * netAmount)/100);
// getRequest().setAttribute("NetAmount", am);
return INPUT;
}
this is my java class method and i want to get data in variable am on jsp page or in javascript function?
You can use in this way :
<%
String var="sth";
%>
<script>
var value = "<%=var%>";
</script>
In Spring MVC, you can add your model to jsp using
ModelAndView mv = new ModelAndView();
mv.addObject("keyForJsp",object); // you can get data in jsp by using the key "keyForJsp"
now to get it in javascript. (using JSTL lib)
<script>
var data = '${keyForJsp}';
</script>
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/
I create and assign values to a list of strings in my controller. I want to assign the list of values to a JavaScript variable. How can I do this?
Controller:
List<string> fruits = new List<string>();
list.Add('Apple');
list.Add('Banana');
list.Add('Kiwi');
ViewBag.FruitList = fruits;
View:
var fruitList = '#ViewBag.FruitList';
When I run the program fruitList comes back as System.Collections.Generic.List 1[System.String]
Way 1:
You can use Html.Raw() and Json.Encode for it:
var fruitList = #Html.Raw(Json.Encode(ViewBag.FruitList));
Way 2:
you can use Json.Parse() in combination with Html.Raw() to parse the raw string in to json:
var fruitList = JSON.parse('#Html.Raw(ViewBag.FruitList)');
Way 3:
you can also use JsonConvert class using NewtonSoft JSON to serialize it to json:
var fruitList = '#JsonConvert.Serialize(ViewBag.FruitList)';
on MyPage.aspx.cs I have List of object
protected List<MyObj> myObjList =null;
protected void Page_Load(object sender, EventArgs e)
{
myObjList = GetObjByUserId("23423");
}
on aspx page I want to assign this list of objects to JS variable
<script type="text/javascript">
$(document).ready(function () {
var BookingsList = <%=myObjList %>;
</script>
but is assign type like string=>
System.Collections.Generic.List`1[myObj]
how I can to assign my collection of object from CS to JS variable?
Try using JavaScriptSerializer like following:
c# Code
Student student = new Student();
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string StudentJson = oSerializer.Serialize(resources);
and in your aspx code get it like:
<script type="text/javascript">
var jsonStudent = <%=StudentJson%>;
</script>
Please make sure that StudentJson is a public or protected property in your backend class
You need to put the list in javascript format. In pure javascript you are looking for the following output (as an example):
var jsList = ['val1', 'val2', 'val3'];
To get this from .NET you need to use the Join function to combine list items into the appropriate format. The complete line of code looks like:
var jsList = <%= "['" + string.Join("', '", myObjList.ToArray()) + "']" %>;
Note that this assumes your "ToString" on your elements generates the output you are looking for and does not include single quotes. Hope that helps!