Use of Eval to transform Razor to Javascript

Asked

Viewed 73 times

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:

inserir a descrição da imagem aqui

Attempt 2:

var data2 = '@listTeste';

Result in HTML interpreted in client:

inserir a descrição da imagem aqui

Attempt 3:

var data3 = '@Json.Encode(listTeste)';

Result in HTML interpreted in client:

inserir a descrição da imagem aqui

Attempt 4:

var data4 = JSON.parse('@Json.Encode(listTeste)');

Result in HTML interpreted in client:

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

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


  1. Is there any other way to perform this procedure?
  2. In that context, the option 2 offers me some security risk?
  3. In terms of performance, taking into account server and client memory allocation and processing, which is the most appropriate?
  4. In relation to the clarity and cleanliness of the code, the option 2 would be the most appropriate?
  5. 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 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?

  • 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.

1 answer

0

You can put the code inside the Eval.

eval('var teste = ' + object );
  • Hello @Denilsonoliveira Thank you so much for your willingness to help. Well, the problem with your answer is that my object that I want to get from js is a C# object and I’m trying to get Razor to "talk" properly with js. Furthermore, at the end of the question, I listed a few points that I would like to see addressed in the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.