Using eval to transform Razor to Javascript

1

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:

  

Ididnotquiteunderstandwhythisattemptdidnotwork...

HomeIcouldputhereseveralotherattempts,butlet'sfinallywork:

Option1:

vardata5=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 do this?
  • In this context, option 2 offers me some security risk?
  • In terms of performance, taking into account memory allocation and server and client processing, which one is most appropriate?
  • Regarding code clarity and cleanliness, would Option 2 be the most appropriate?
  • And if my Javascript is a .js separate from .cshtml , would I have to leave the data in a global variable to have access there?
  • asked by anonymous 06.10.2017 / 00:15

    1 answer

    0

    You can put the code inside the eval.

    eval('var teste = ' + object );
    
        
    06.10.2017 / 13:42