1
Before criticizing the use of eval
, I read and recommend that answer.
Take into account the following context:
Code C# (Razor):
var teste = new
{
prop1 = 123,
prop2 = "minha mãe disse 'Háaaaaa!'"
};
var listTeste = new object[2];
listTeste[0] = teste;
Now I need to receive this data in a variable Javascript, as an object.
Attempt 1:
var data1 = @listTeste;
In Visual Studio 2013 the editor shows line error, since after the
=
no more Javascript.
Result in HTML interpreted in client:
Attempt 2:
var data2 = '@listTeste';
Result in HTML interpreted in client:
Attempt 3:
var data3 = '@Json.Encode(listTeste)';
Result in HTML interpreted in client:
Attempt 4:
var data4 = JSON.parse('@Json.Encode(listTeste)');
Result in HTML interpreted in client:
I don’t quite understand why this attempt didn’t work...
I could put here several other attempts, but let’s go the ones that finally worked:
Option 1:
var data5 = JSON.parse("@Html.Raw(HttpUtility.JavaScriptStringEncode(Json.Encode(listTeste)))");
Option 2:
var data6 = eval(@Html.Raw(Json.Encode(listTeste)));
- Is there any other way to perform this procedure?
- In that context, the option 2 offers me some security risk?
- In terms of performance, taking into account server and client memory allocation and processing, which is the most appropriate?
- In relation to the clarity and cleanliness of the code, the option 2 would be the most appropriate?
- And if my Javascript is a
.js
separate from the.cshtml
, I would have to leave the data in a global variable to have access there?
Did you see this one? https://answall.com/q/128845/101
– Maniero
@Maniero at the end of your answer you say: "The JS problem is lower." Could I talk about this in an answer to that question, please?
– Jedaias Rodrigues
Ih, there would be a lot to talk about :) And I think the context of the question is quite different. http://wiki.c2.com/? Javascriptsucks and https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f and https://whydoesitsuck.com/why-does-javascript-suck/ and the fact that most JS programmers are unaware of what they are doing on something that exposes security.
– Maniero