Combine MVC .NET Razor with Javascript to build an array - javascript

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

Related

how to make index dynamic for json objects

i'm tring to dynamically display eveyrthing that comes back from the server, however to get it displaying i have to explicitly write in the index of the object i'm trying to access, how can i make this dynamic so it goes through them all?
i am Using AngularJS, Express, and Mongoose.
here is the code snippet where the index i want to change on its own located.
app.controller('MainController', ['$scope', 'whipmeet', function($scope, whipmeet) {
whipmeet.getWhipmeets(function(JSON){
$scope.meetinfo = JSON;
$scope.meetparts {
name = JSON.data["0"].name,
location = JSON.data["0"].location,
car = JSON.data["0"].car,
date = JSON.data["0"].date,
time = JSON.data["0"].time,
type = JSON.data["0"].type,
stock = JSON.data["0"].stock
};
what i'm trying to achieve is that the ["0"] index change dynamically to get all the indexes of the objects so i can get those zeroes to go 1 to 2 to 3 and so on untill there are no more
There are few options.
From my understanding, you are trying to iterate through the JSON object that is returned to you.
You can either use:
var meetpartList = [];
JSON.foreach(function(d) {
// do your parsing here
newObject = {};
newObject.name = d.name;
// etc..
meetpartList.append(newObject);
});
or you can use:
for (int i = 0; i < numberOfIndicesInJson; i++) {
// get values using JSON[i + ""].key;
}
to do something similar as above to create a list of meets.
Then you can use that list of meets to render into your view using ng-repeat, which I hope is the solution you're looking for?

Is it best practice to store data in HTML tags that don't have any content?

Is it bad practice to do this in a template, or is there a better alternative? Is it okay to have an empty span like this in my code?
<span class="stored-id-number" data-idnumber="1234"><!-- empty --></span>
The reason I ask is because this currently seems to be the only way that I can store some data about multiple items that each live in a different template structure, and then reliably retrieve that data with JavaScript, like so:
// get all instances of this data item - where ever they may be
$('.stored-id-number').each(function (item) {
var idNumber = $(this).data('idnumber');
// do something with ID number in relation to this item
});
I seemed to me strange to add an empty span element just to store some data. But at the moment it seems like the only reliable way that I can do it.
It is designed for this in HTML5.
More about data-* here: http://www.w3schools.com/tags/att_global_data.asp
Alternatively you could do:
<script>
var store = {
"myStoreId": 1234,
"myOterStoreId": 9876,
}
</script>
Access it by:
store["mystoreId"]
or
for (storeId in store) {
var idNumber = store[storeId]
}
EDIT: Maybe you simple want an Array of "storeIds" ? Do it like that:
<script>
var store = [
1234,
9876,
]
</script>
Access it by:
store[index]
or
for (var i = 0; i < store.length; ++i) {
var idNumber = store[0]
}

Call JavaScript function with Razor syntax

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

how to parse json array

I'm trying to parse something like this
{
"popular result":[
{"term":"Summer","url":"http://summer.com"},
{"term":"Autumn","url":"http://autumn.com"},
{"term":"spring","url":"http://spring.com/"},
{"term":"winter","url":"http://winter.com/"}]
}
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i = 0; i < json.length; i++) {
$.each(myJson.i, function (key, value) {
alert(value.term);
});​
}
});
});
</script>
but nothing happened! Because is array in array! Please let me know how to do this
Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.
Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn't a space) is the array (in JSON those show up at []) you want to traverse.
For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn't exist (which didn't crash b/c it never got there).
Cleaning it up...
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i=0;i<json['popular result'].length;i++) {
alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
}
});
});
</script>
Notice how the alert references the json object (that's your variable name), the popular result array, then [i] is the "row" in that array, and the term/url element of the object on that row.
NOTE: Running something with a ton of alerts as you're debugging is annoying. Check out console.log.
You don't need $.each and you need to loop over the array set as the value of popular result which is inside a containing object.
$.getJSON('/Controls/GetPopularSearches', function (json) {
var arr = json['popular result'];
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].term);
}
});
Demo.
Check this fiddle
var jsontext =
'{"popularresult":[{"term":"Summer","url":"http://summer.com"},{"term":"Summer","url":"http://summer.com"}]}';
var getContact = JSON.parse(jsontext);
for (i = 0; i < getContact.popularresult.length; i++) {
alert(getContact.popularresult[i].term);
}
http://jsfiddle.net/ae8gd/
If you get the jsonObject as shown then
var JsonArray=json.popular; //get jsonArry
$.each(JsonArray,function(i,val){
// do logic
});
To parse json use JSON.parse();

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