ASP.Net Model to Javascript - Passing Data from server to client - javascript

Hey guys quick question what is the best approach on converting Model to Javascript.
I tried using this
#{
var arr = new string[3];
arr[0] = "1";
arr[1] = "2";
arr[2] = "3";
var jason = JsonConvert.SerializeObject(Model);
}
<script type="text/javascript">
var string = '#jason';
var variable2 = jQuery.parseJSON(string);
alert(variable2.Id);
</script>
as you can guess it did not work, I look through the sample of jQuery which should work but I am not sure if it is compatible with JsonConvert of .net
Its my first time on programming in the client side so this is quite a simple question but I tried looking the answer from the net. Mostly I see are uber complicated answers and at least 3 and higher old so I am guessing there should be an easier way to do this now?

I feel like this needs an answer because it's the number 2 result from google and has been viewed over 200 times, and as stated by the OP every other answer is generally long and/or convoluted. But the simplest answer is:
Javascript added to your aspx page:
<script type="text/javascript">
var myObject = <%=JsonConvert.SerializeObject(MyNetObject)%>;
</script>
The key bit being that your output of HTML looks as follows:
<script type="test/javascript">
var myObject = {"Prop1":"value1","Prop2":"Value2"};
</script>
Javascript natively handle JSON so you don't need to reparse anything on the client side. If the object is properly serialized it will be recognized without further conversion (this includes lists and object properties).
In the example provided in the OP the resultant Javascript object would be a simple array. So access to the elements on the client side would be:
alert(variable2[0]), alert(variable2[1]), alert(variable2[2])....
In order to provide the Javascript property calling functionality that OP is trying to do on the client side would require the following on the server side:
var json = JsonConvert.Serialize(new { ID1 = 1, ID2 = 2, ID3 = 3 });
In which an object with Named properties is serialized into the page.

Related

Can a Parse Object be manipulated outside of Cloud Code?

I think Parse has made some changes to its objects without providing a clear memo. I built my app with Node and most of the code rests on my server instead of Cloud Code. Recently I've noticed a number of errors on code that previously tested well. At first I thought it was security settings or Parse versions (I'm currently using the latest version, 1.6.7). I reverted back and updated and nothing has helped with this issue save for transporting my code to the cloud.
I look forward to real help/suggestions, I've already looked at the docs and I'm not finding what I need so please save your breath if you were to suggest that comment. Here is some example code illustrating the problem:
var Parse = require('parse/node');
Parse.initialize("app key", "JS key", "master key");
//for this example the app key and JS key may be backward but they are correct in the project.
var array = [{key: value}, {key1: value1}, {key2: value2}]
var Object = Parse.Object.extend("Table");
var objectQuery = new Parse.Query(Object);
objectQuery.first({
success: function(result){
var Id = result.get("user").id//this correctly provides me with the ID!
_.each(array, function(n){
_.mapObject(n, function(v, k){
var Next = Parse.Object.extend("Info");
var nextQuery = new Parse.Query(Next);
nextQuery.equalTo("name", k);
nextQuery.find({
success: function(Row){
var problem1 = _.map(Row, function(n){return _.find(n)})
console.log(problem1);//this used to show me the JSON
key value pairs if it were an object or the array or
whatever, now I just get ['Info'] from the console.log.
var problem2 = _.map(problem1, function(n){return
_.extend(n, {id: userId})});//this far ['Info']
has proven completely impenetrable. Granted I've used
underscore here but I've tried operations with basic
javascript functions like concat and any data within the
Parse Object is completely ignored. I'd like to do other
stuff from here but there is no point as I can't get
beyond 'undefined' should I try doing anything else with `the data.`
}})})})}})
I'm desperate to move on from this and I believe it is something idiosyncratic. I've scoured Stack Overflow and other sources for days now trying to figure it out. Clearly I need some hand holding and I'm desperate to move on. Thanks.

Passing Applescript list to javascript ExtendScript as array for Indesign

Background
I have a load of Applescripts(AS) which designers use with InDesign that help process the workflow for production. There is a great deal of OS interaction that the AS does that the JavaScript can not, so moving away from AS is not possible.
Due restrictions I am unable to install pretty much anything.
I am unable to update anything. Script Editor and ExtendScript Tool Kit are what I have to work with.
Operating Environment:
OS X 10.8.5 &
Adobe CS6
How it works
User preferences are saved as Properties in local Applescripts saved in the user's documents folder.
###property grabber.scpt
set mypath to path to documents folder
set mypropertiesfile to ((mypath & "myproperties.scpt") as string)
set thePropertyScript to load script file mypropertiesfile
set designerinitials to (designerinitials of thePropertyScript) ETC...
Some of the properties are AS lists.
Why I need JS?
I'm making palettes and would prefer to use the ScriptUI rather than do it all in AS like this:
set dlgRef to make dialog with properties {name:"User Settings", can cancel:true, label:"Dialog Label"}
The string the AS hands off to the JS is this:
{"myname",{firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"},{firstvalue:"test2", secondvalue:"val2", thirdvalue: "val3"}}
These are not lists, but text...
The JS
myAppleScript = new File("valid_path_to/property grabber.scpt");
var myreturn = app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage);
var myname = myreturn[0];
var firstlist = myreturn[1];
var secondlist = myreturn[2];
ExtendScript data browser shows:
firstlist = {firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"}
It is not an array...
I have tried using https://github.com/KAYLukas/applescript-json
to json encode the lists, but the same result.
firstlist = [{firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"}]
I have also made it much simpler with just
firstlist = {"test","val2","val3"}
Still the JS treats it as a string and not an array.
Any ideas what I need to do or am doing wrong? I hope it simple and I feel stupid if I get an answer...
Glad you have something that works, but if you're passing text to ExtendScript, why not format it on the AS side to be ExtendScript-friendly, like ['firstvalue', 'secondvalue', 'thirdvalue"'] --but this would be a string in AS, like
--in AS:
"['firstvalue', 'secondvalue', 'thirdvalue"']"
Then, in ExtendScript, if that's in a variable, like, myData, you can do (as I just did in ExtendScript Toolkit):
//in JS:
myArray = eval(myData);
I know using eval() is evil in web work, but for ExtendScript stuff, it can be very useful.
I hate finding an answer after I take the time to post an elaborate question.
https://stackoverflow.com/a/14689556/1204387
var path = ((File($.fileName)).path); // this is the path of the script
// now build a path to another js file
// e.g. json lib https://github.com/douglascrockford/JSON-js
var libfile = File(path +'/_libs/json2.js');
if(libfile.exists)
$.evalFile(libfile);
Like Neo learning Kung Fu, it suddenly went, "Whoa, I know JSON!"
var firstlist = JSON.parse(myresult[1]);
Gives me workable objects
doScript can pass script args to one language to another. Here is a snippet inspired from the doc:
var aps = "tell application \"Adobe InDesign CC 2014\"\
tell script args\
set user to item 1 of {\"John\", \"Mike\", \"Brenda\"}\
set value name \"user\" value user\
\"This is the firest AppleScript script argument value.\"\
end tell\
end tell"
app.doScript(aps, ScriptLanguage.applescriptLanguage);
var user = app.scriptArgs.getValue("user");
alert( user+ "from JS" );
I don't think script args would return anything else than strings even if those could represent any kind of value. However a string can be easily turned into an array with a split method like this :
var aps = "set ls to {\"john\", \"mark\"}\
set n to count of items of ls\
set str to \"\"\
repeat with i from 1 to n\
set str to str & item i of ls\
if i < n then\
set str to str & \",\"\
end if\
end repeat\
tell application \"Adobe InDesign CC 2014\"\
tell script args\
set value name \"str\" value str\
end tell\
end tell";
app.doScript(aps, ScriptLanguage.applescriptLanguage);
var str = app.scriptArgs.getValue("str");
var arr = str.split(",");
alert( "Item 1 of APS list is \""+arr[0]+ "\" in the JS context" );
The idea is to flatten the APS list into a comma separated string that will be later splitted in the javascript context to turn it into an array.

How to parse a JSON array

new here and hit a roadblock, been searching but can't find the answer with my skill set. Task is pretty simple, I want to parse this http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json which is from a weather station. I have used the W3C tutorial but just can't seem to parse this file, but http://json.parser.online.fr has no problem. All the looping parse examples just give me alert after alert.
All I want is the ability to select temp[0] (out of god knows how many) for example via javascript and have it display on a website. I'm really lost, tried searching and if I've missed the goldmine then my bad. Thanks!
Example code
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌​43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌​43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.temp[0];
First, you need to parse the incoming string as below:
temp_arr = JSON.parse(json_string);
Just loop over the temp_arr array, and in each iteration of loop you'll have one object (tobj). For example, like this:
{"humidity":"40.9000","stationtime":"2014-07-06 21:21:03","temp":"22.6000","timestamp":"2014-07-06T11:20:27.231Z"}
All you have to do is, access it like tobj.temp and use it to display on page.
I have written a jquery implementation at: http://jsfiddle.net/DNH5n/2/
Jquery makes working with JSONP much easier heres an example (http://jsfiddle.net/icodeforlove/9mBsr/)
$.getJSON('http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?callback=?', function (data) {
data.forEach(function (item) {
$('body').append(JSON.stringify(item));
});
})
update again
heres another example using your code (http://jsfiddle.net/icodeforlove/9mBsr/2/)
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj[0].temp;

Array constructor "new Array()" can be overwritten and replaced with malicious code, how?

We can create an array in a couple of ways:
var myArray = new Array();
Or:
var myArray = [];
The second way is safer to use than the new Array() syntax, because the Array constructor can be overwritten and potentially replaced with malicious code.
I have seen above lines in many JavaScript books but I don't understand how an Array constructor can be overwritten and replaced with malicious code? I'm looking for an example of how someone can do it, so that I can understand the reality of the issue.
Somewhere in the code above:
Array.prototype.forEach = function (e){
console.log("something wrong there");
return(e);
};
Somewhere in the code below:
var i = [1,2,3,4,5];
i.forEach(function(e){
console.log(e);
});
Output:
>"something wrong there"
As you can see, there is no difference how to initialize array variable. var i = []; just shorter notation.
If you write on your JS console :
[1,2,3]
(just like that) - you can do nothing with it.
Well that's not accurate with old browsers.
You could overload the array ctor by :
Array = new function (){... }
and so , when you got your friend list via Json ( not jsonp) : -
someone could use an XSS/XSF attack and steal your friends list.
The thing ere is the fact that : if you write [1,2,3] - there is actually a ctor working here.
So if you got to a website which does array response - he could still your list.

Is there a way to change the following VBScript into javascript?

I'm attempting to convert some VBScript to javascript, but I doubt it's possible because it seems to be specific to MS apps and code. I'd like help with either of the two possible outcomes: a) actually converting the code to javascript, or b) demonstrating that converting it to javascript is currently not possible.
The specific VBScript statements that I consider too MS-specific are:
set oExcel = CreateObject("Excel.Application")
set oBook = oExcel.Workbooks.Add
oBook.HTMLProject.HTMLProjectItems("Sheet1").Text = sHTML
oBook.HTMLProject.RefreshDocument()
oExcel.Visible = True
oExcel.UserControl = True
Has anyone interfaced javascript and Excel well enough for a solution to exist?
Sure like this:-
var excel = new ActiveXObject("Excel.Application")
var book = excel.Workbooks.Add()
//The line below doesn't work in Excel 2007
// book.HTMLProject.HTMLProjectItems["Sheet1"].Text = sHtml
var sheet = book.Sheets("Sheet1")
sheet.Range("A2").Value = "Hello World"
excel.Visible = true
excel.UserControl = true
You can do this only with JScript, not JavaScript- this will show you how. This may be fine if you are using only IE.

Categories

Resources