Before criticizing the use of eval
, I read and recommend this answer .
Consider the following context: Home C # Code (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 get this data in a Javascript , as an object.
Try 1:
var data1 = @listTeste;
In Visual Studio 2013 the editor shows error in the line, since after
=
no more JavaScript.
Result in the interpreted HTML in the client:
Attempt2:
vardata2='@listTeste';
ResultintheinterpretedHTMLintheclient:
Try3:
vardata3='@Json.Encode(listTeste)';
ResultintheinterpretedHTMLintheclient:
Attempt4:
vardata4=JSON.parse('@Json.Encode(listTeste)');
ResultintheinterpretedHTMLintheclient:
HomeIcouldputhereseveralotherattempts,butlet'sfinallywork:Ididnotquiteunderstandwhythisattemptdidnotwork...
Option1:
vardata5=JSON.parse("@Html.Raw(HttpUtility.JavaScriptStringEncode(Json.Encode(listTeste)))");
Option 2:
var data6 = eval(@Html.Raw(Json.Encode(listTeste)));
.js
separate from .cshtml
, would I have to leave the data in a global variable to have access there?