System.Collections.Generic.List from CS to Js variable - javascript

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!

Related

Constructing a string array with Frida

I'm trying to call a function with Frida that takes a string array as one of its arguments.
public void coolFunction(long value, String[] strArr);
Within Java it gets called like this:
long importantValue = 4L;
String[] importantArr = new String[]{"TEST"};
coolFunction(importantValue, importantArr);
The overload looks like this: .overload('long', '[Ljava.lang.String;')
I could probably create a string array from scratch, but I don't know how to express it in Javascript. What's the Frida equivalent of new String[]{"TEST"}?
Because of that I tried to turn an ArrayList<String> into a String[], which also wasn't successful.
As far as I can tell there are two simple ways to turn ArrayList<String> into String[]:
Attempt #1:
List<String> list = new ArrayList<String>();
list.add("TEST");
String[] stringArray = list.toArray(new String[0]);
If I try to express it with Javascript it looks like this:
var AL_class = Java.use("java.util.ArrayList");
var arrList = AL_class.$new();
arrList.add("TEST");
var stringArray = arrList.toArray(Java.use("[Ljava.lang.String;").$new(0));
This fails with the following error message:
Error: no supported overloads
Attempt #2:
List<String> list = new ArrayList<String>();
list.add("TEST");
Object[] objectArray = list.toArray();
String[] stringArray = (String[]) objectArray;
Javascript:
var AL_class = Java.use("java.util.ArrayList");
var arrList = AL_class.$new();
arrList.add("TEST");
var arrayButAsObject = arrList.toArray();
var stringArray = Java.cast(arrayButAsObject, "[Ljava.lang.String;");
This fails because it assumes that I want to use Javascript's toArray() function.
The solution to this problem is probably very simple but I've been stuck here for quite a while now and can't seem to figure it out. Any help would be appreciated.
Instead of trying to construct a java.util.List and then convert it to an array I would use the Frida function Java.array and directly construct a Java String array:
var javaStringArray = Java.array('java.lang.String', [ "Test" ]);

Accessing a java HashMap from JSP page using JavaScript

I have a controller class in Spring MVC, where i am returning a HaspMap as Model attribute -
#ModelAttribute("regPrefix")
public Map<String, String> getRegPrefixesOfDepartmentforGroup(final Model model, final HttpServletRequest request) {
final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, regPrefix);
return regPrefixOfDept;
}
Now in the corresponding JSP page, i am trying to access the Hashmap and store the key/value pairs of the Hasmap in a variable using JavaScript. I am trying like below but its not right. Can anyone suggest how to do that
<script>
$("#deptIdSelection").change(function()
{
var obj = document.getElementById("deptIdSelection");
var textItem = obj.options[obj.selectedIndex].text;
alert(textItem);
var mapObj = "${regPrefix}";
for(var key in mapObj)
alert(key +" ->"+ mapObj[key]);
}
);
</script>
Try to access map values like this:
${regPrefix.key}
If you want to iterate through the map keys, it is not so easy: JSTL is executed on the server side and is rendered to a plain text - no JavaScript objects are created. The following line var mapObj = "${regPrefix}"; will be rendered to a string representation of HashMap, not to a JavaScript object.
To convert your map to a JavaScript object I suggest you to use one of the following methods:
1) Convert your map to JSON and pass it as a String. So when it is rendered to a JavaScript code, it will look like a regular JS object: var mapObj = {"key": "value", ...};. You can use Gson or any other JSON library to achieve this:
final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, new Gson().toJson(regPrefixOfDept));
And then var mapObj = ${regPrefix}; (note that you need no quotes around because you want mapObj to be a JS object, not a string)
2) Iterate through your map using <c:forEach> to generate a JS object:
var mapObj = {
<c:forEach items="${regPrefix}" var="item" varStatus="loop">
${item.key}: '${item.value}' ${not loop.last ? ',' : ''}
</c:forEach>
};
In both cases you should be able to then call
for(var key in mapObj)
alert(key +" ->"+ mapObj[key]);

How to get attributes in Json String in servlet

How can I get each attribute within a Json String?
I got the Json by converting first my array of objects in JavaScript via JSON.stringify. Afterwards I used ajax to pass the string to my servlet.
Servlet Code:
String data = request.getParameter("jsonData");
System.out.println("json data: " + data);
Result:
[{"courseID":"1","codePI":"PO-BSINSYS-02.01","curriculumID":"3"},
{"courseID":"2","codePI":"PO-BSINSYS-02.02","curriculumID":"3"}]
What I want is to get the individual values of the json so that I can assign them later to my object.
E.g.
ArrayList<Curriculum> arrCur = new ArrayList<>();
for (int x = 0; x < array.size(); x++) {
Curriculum cur = new Curriculum();
cur.setCourseID(courseID[x]);
cur.setCodePO(codePI[x]);
cur.setCurriculumID(curriculumID[x]);
arrCur.add(cur);
}
As "crowder" mentioned, you need to parse the json.
There are several ways to do it.
low-level libraries that would convert your string into a
JSONObject which is sort of a map (with keys "courseID", "codePO"
etc). At the time I used fasterxml but I see a newer approach here:
http://crunchify.com/java-how-to-parse-jsonobject-and-jsonarrays/
Higher-level libraries that would map the json directly into
Java business Objects such as "Curriculum". My own experience was
focused on replacing the simple Servlet with Spring - see for
example https://spring.io/guides/gs/rest-service/
good luck
You can use this way if you are sending arry of object from javascript and if you class -
class Curriculum{
Integer courseID;
String codePI;
Integer curriculumID;
}
Use like this -
String data = request.getParameter("jsonData");
JSONArray jsonArray = new JSONArray(data);
java.lang.reflect.Type curriculumType =new com.google.gson.reflect.TypeToken<List<Curriculum>>(){}.getType();
List<Curriculum> curriculum = new GsonBuilder().create().fromJson(jsonArray.toString(), curriculumType);
This will assign list of Curriculum. Hope this will help you.
You can also use jackson-databind API to convert your json to java object.
Create your bean for Curriculum.
class Curriculum{
Integer courseID;
String codePI;
Integer curriculumID;
public Integer getCourseID() {
return courseID;
}
public void setCourseID(Integer courseID) {
this.courseID = courseID;
}
public String getCodePI() {
return codePI;
}
public void setCodePI(String codePI) {
this.codePI = codePI;
}
public Integer getCurriculumID() {
return curriculumID;
}
public void setCurriculumID(Integer curriculumID) {
this.curriculumID = curriculumID;
}
}
Following is the code to convert your json to Curriculum object
JSONArray jsonArray = getJSONArray();
ObjectMapper objectMapper = new ObjectMapper();
for(int i =0;i<jsonArray.length();i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
//convert json string to object
try {
Curriculum curr= objectMapper.readValue(jsonData.toString().getBytes(), Curriculum.class);
System.out.println(curr);
} catch (Exception e) {
e.printStackTrace();
}
}

how can i get variable data from java class to javascript?

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>

How to iterate a C# generic list in javascript? [duplicate]

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)]));

Categories