Call JavaScript function with Razor syntax - javascript

I am currently working on an ASP.Net MVC application.
From my database, I have created three dictionaries and stored them inside a View Model.
After populating said dictionaries with some logic in the controller, I'm accessing these dictionaries in my View via #Model
After manipulating these dictionaries, I need to send the data to a JS function to apply some logic to a JS library called DHtmlxScheduler
I have read about the Razor syntax using #: and am currently using this method to send two string arrays. when trying to access these arrays in the JS function, they only appear to hold System.String[]
Here is the code:
var weekArray;
var engArray;
#foreach(var week in Model.WeeklySchedule)
{
var key = week.Key;
var values = week.Value.ToArray();
var eng = Model.EngineerSchedule.Where(k => k.Key == key).Select(v => v.Value).ToArray();
string test = "hello";
#: gatherTimes('#values', '#eng');
}
function gatherTimes(values, engs)
{
for(var i = 0; i < values.length; i++)
{
alert(values[i]);
}
//alert(values);
//alert(engs);
//weekArray[weekArray.length] = values;
//engArray[engArray.length] = engineers;
}
I eventually plan on looping through the arrays, they hold information about time slots and engineer IDs. If there is any more information I may provide, I will do my best to do so.

You will need to encode the list to JSON using JSON.Encode. Here is an example:
#{
// C# collection
var collection= new List<string> {"A", "B", "C"};
}
<script type="text/javascript">
// encode C# collection to JSON, set to javascript variable
var arr = #Html.Raw(Json.Encode(collection))
for(var i = 0; i < arr.length; i++)
{
console.log(arr[i]); // Output is A B C
}
</script>
In your case it would be like so:
#: gatherTimes('#Html.Raw(Json.Encode(values))', '#Html.Raw(Json.Encode(eng))');

Related

Display Java List values in Javascript alert

I have a Java list whose values I need to display in Javascript.
Here is my Java code to populate the List:
List<CoordinateVO> coordinateList = new ArrayList<CoordinateVO>();
for (Iterator iterator2 = cordinates.iterator(); iterator2.hasNext();) {
Adcoordinate object = (Adcoordinate) iterator2.next();
if(object!=null){
CoordinateVO co = new CoordinateVO(object.getLatitude(),object.getLongitude());
coordinateList.add(co);
}
}
Now I want to display values of CoordinateList in Javascript Dialog Box.
Is there any way out to do this ?
Finally I found the solution ,
I converted the java.util.List into Json Array in java code and then in Javascript I parse the Json Array .
Here is my Java Code
String json = new Gson().toJson(coordinateList); // List Conversion to Json Array
dataVO.setCoordinateArray(json);
In Javascript
<script>
var myObject=JSON.parse(dataVO.adScript);
var index;
for (index = 0; index < myObject.length; ++index) {
alert("Test Latitude "+myObject[index].latitude);
alert("Test Longitude "+myObject[index].longitude);
}
</script>

Javascript storing multiple fields in an array

I was wondering if it's possible to store multiple different fields in a dynamic array using Javascript.
In Informix it is called a dynamic array of records and it is accomplished like this
# define array of record
la_data dynamic array of record
var_idno integer,
var_desc char(30)
end record
# populate array of record
for lv_cnt = 1 to 10
let la_data[lv_cnt].var_idno = lv_cnt
let la_data[lv_cnt].var_desc = "dummy data"
end for
# use stored data
display la_data[5].var_idno # will output 5
display la_data[5].var_desc # will output dummy data
How would I do something similar (or completely different) using Javascript
// define array of record
var la_data = [];
// populate array of record
for (var lv_cnt = 1; lv_cnt <= 10; lv_cnt++) {
// This initializes an object we can put your properties on
la_data[lv_cnt] = {};
la_data[lv_cnt]['var_idno'] = lv_cnt;
la_data[lv_cnt]['var_desc'] = "dummy data";
}
// use stored data
console.log(la_data[5].var_idno) // will output 5
console.log(la_data[5].var_desc) // will output dummy data
Fiddle: http://jsfiddle.net/xxqkfuot/
As you can see in other answers there are simpler ways to do this but I was attempting to keep the code as similar as possible so you could see the connection between the lines.
I suppose you could create sometihng like a dynamic array in javascript, but the simplest and most idiomatic thing to do with pure javascript would be to use a list:
var list = [];
for (i = 0; i < 10; i++)
list.push({var_idno: i, var_desc: 'Dummy data'});
JavaScript is loosely typed so this is actually too easy to do.
var one = 1;//int
var two = "String";//String
var three = {
"name": "Foo",
"address": "bar"
};//Object
var array = [one, two, three];
console.log(array[0]);//1
console.log(array[1]);//String
console.log(array[1]);//[Object]

Combine MVC .NET Razor with Javascript to build an array

I'm passing a List from my controller to a view, where I want to be able to take the Model and loop through results in JQuery/Javascript. I'm having a heck of a time figuring out how to do that.
My controller returns a list of colors. In the view, I converted the List to an array. I then pass it to my where I'm trying to loop through it to build an array I can using in my JS.
<script>
$(document).ready(function () {
var currentView = sessionStorage.getItem('lastView');
var jsArr;
for (i=0; i<#arr.Length; i++) {
jsArr.push(#arr[i])
}
if (!currentView) {
sessionStorage.setItem('lastView', 0);
$("body").css("background-image", "url('/Images/Home/#arr[0].Location')");
} else {
sessionStorage.setItem('lastView', currentView++);
}
})
</script>
There has to be an easy way of doing this...
<script>
$(document).ready(function () {
var currentView = sessionStorage.getItem('lastView');
var jsArr = #Html.Raw(Json.Encode(arr)) ;
if (!currentView) {
sessionStorage.setItem('lastView', 0);
$("body").css("background-image", "url('/Images/Home/#Html.Raw(arr[0].Location)')");
} else {
sessionStorage.setItem('lastView', currentView++);
}
})
</script>
I would instead return json from the server. However if you want to do it in an html view I think something like this might work:
var jsonObj = '#Html.Raw(Json.Encode(Model.arr))'
//the loop is unnecessary, but can be useful if you need additional processing
var myArray = [];
for (i=0; i<jsonObj.length; i++) {
myArray.push(jsonObj[i])
}
Here is a way to manually build a JSON or JS object with razor code, some very easy to use code:
#foreach (var item in Model.Users)
{
<text>
UserData[UserData.length] = {
"UserID": '#item.ID', "FullName": '#item.Name'
};
</text>
}
I purposefully showed model property names being used and JSON property names being different to show an advantage of manually building the array.
Also, in this case you would be able to send a model through with multiple collections of data. Then just iterate through that collection (#foreach (var item in Model.Users)) with your Razor code to build your JSON or Javascript object array

How to copy multidimensional array from Java request variable to Javascript variable in a JSP page?

I need to get the contents of a multidimensional array, passed in as a String [][] saved in a request variable, and put its contents in a Javascript variable.
The "String [][] dataArray" variable holds the values I expect. Example:
dataArray[0][0] = "Joe"
dataArray[0][1] = "Smith"
dataArray[0][2] = "901-555-1212"
dataArray[1][0] = "Jane"
dataArray[1][1] = "Smith"
dataArray[1][2] = "901-555-9999"
This doesn't work:
Java
request.setAttribute("passedInArray", dataArray);
Javascript (inside JSP page)
var jsArray = <%= request.getAttribute("passedInArray");%>
How can I get the contents of passedInArray into jsArray? Thanks in advance!
If you need to use a String[][], you would need to iterate over the rows in passedInArray on the server side.
var dataArray = new Array();
<c:forEach var="row" items="${passedInArray}">
dataArray.push(['${row[0]}', '${row[1]}', '${row[2]}']);
</c:forEach>
An alternative would be to serialize your array into a JSON string. There are good java libraries like Jackson and Gson available for the job. Basically, they would be accomplishing the same as if you were to code it like this:
StringBuffer sb = new StringBuffer("[");
for (int i = 0; i < dataArray.length; i++) {
sb.append("[");
for (int j = 0; j < dataArray[i].length; j++) {
sb.append("'" + dataArray[i][j] + "'");
if (j < dataArray[i].length-1)
sb.append(',');
}
sb.append("]");
if (i < dataArray.length-1)
sb.append(',');
}
sb.append("]");
request.setAttribute("passedInArray", sb.toString());
Then in your jsp, you would just declare it as a javascript variable and use it:
var dataArray = ${passedInArray};
console.log(dataArray.length);
console.log(dataArray[0].length);
No matter how you do it, you need to do work on the server side to transform your java array into String(s) that javascript can use directly.

accessing session variables in javascript inside jsp

I need to provide data for google APIs table... so I'll send it from servlet to JSP
but how can I access this data in "googles" javascript?
I'll provide sample of another JS - very simple one - just to let me learn how to make what topic says
<script>
function showTable()
{
<%
Object obj = session.getAttribute("list");
List<String> list = new ArrayList<String>();
int size = 0;
if (obj != null) {
list = (ArrayList<String>) obj;
size = (Integer) session.getAttribute("size");
}
for (int i = 0 ; i < size ; i++) {
String value = list.get(i);
%>
alert('<%= i %> = <%= value %> ');
<%
}
%>
}
</script>
It has to print elements of given list... but now it's just a big scriplet with alert inside of it... for to refactor it? I don't like having to much java in JSPs, because servlet is where it should be placed
EDIT: just to sum up - I would prefer "normal" JS for loop here... Generally I'd prefer to minimize java code, and maximize JS
Convert it to JSON in doGet() of a preprocessing servlet. You can use among others Google Gson for this. Assuming that you've a List<Person>:
List<Person> persons = createItSomehow();
String personsJson = new Gson().toJson(persons);
request.setAttribute("personsJson", personsJson);
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
(note that I made it a request attribute instead of session attribute, you're free to change it, but I believe it doesn't necessarily need to be a session attribute as it does not represent sessionwide data)
Assign it to a JS variable in JSP as follows:
<script>
var persons = ${personsJson};
// ...
</script>
This way it's available as a fullworthy JS object. You could feed it straight to the Google API.
Now invoke the URL of the servlet instead of the JSP. For example, when it's mapped on an URL pattern of /persons, invoke it by http://localhost:8080/contextname/persons.
JavaScript is executed at client side, and scriptlets, EL, and JSP tags at server side. From the point of view of the server-side code, JavaScript is just generated text, just like HTML markup.
So, if you want to have a JavaScript loop which loops over a JavaScript array in the generated HTML page, you need to generate the JavaScript code which initializes the array, and the JavaScript loop.
Here's the JSP code
var theArray = [<c:forEach items="${sessionScope.list}" var="item" varStatus="loopStatus">'${item}' <c:if ${!loopStatus.last}>, </c:if></c:forEach>];
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
This JSP code will generate the following JavaScript code, assuming the list in the session attribute contains "banana", "apple" and "orange":
var theArray = ['banana', 'apple', 'orange', ];
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
Make sure, though, to properly escape the values of the list in order to generate valid JavaScript code. For example, if one of the values was "I'm cool", the generated JavaScript would be
var theArray = ['I'm cool', 'apple', 'orange', ];
which is not valid anymore. Use commons-lang StringEscapeUtils.escapeEcmaScript to escape the values.
since the ArrayList is having objects of Strings you can simply use split() method on the value of the array list. Something like as below;
function showTable() {
<%
Object obj = session.getAttribute("list");
List list = null;
if (obj != null) {
list = (ArrayList<String>) obj;
} else list = new ArrayList<String>(); %>
var jsList = <%=list.toString()%>
//remove [] from content
jsList = jsList.replace("[","");
jsList = jsList.replace("]","");
//split the contents
var splitContent = jsList.split(","); //an array of element
for(var i=0;i<splitContent.length;++i) {
alert(splitContent[i]);
}
}
I hope this will help you solve this.

Categories