Razor Syntax in JavaScript Code Block

I want to know if it is good to use a razor in JavaScript code. For instance:

<script type="text/javascript"> var variable = @some.Id </script> 

Or is it better to create a hidden value and then take it using JavaScript, for example?

 <input type="hidden" id="someId" value"@some.Id" /> <script type="text/javascript"> var variable = $('#someId').val(); </script> 

EDIT:

 @{ var formVariables = serializer.Serialize(new { id = Model.Id, name = Model.Name, age = Model.Age }); <input type="hidden" id="header_variables" value="@formVariables"/> <script type="text/javascript" src = "/Scipts/..."></script> } 

This is a good decision?

+4
source share
3 answers

I personally would go with the extension of the second option and create a separate .js file. The reason is that if you delegate the work to a third party to take care of the jQuery / javascript parts of the user interface, then they should not have any signs of backend functionality.

There are many ways to use the html5 attributes (i.e. data-attribute = 'foo') on the inputs, which will allow you to "decorate" your inputs with a load of properties that can be analyzed inside an external .js file.

A very brief example:

In your opinion:

 <input type='text' id='myId' data-action='@Url.Action("MyAction")' class='myClass' /> 

in your .js file:

 var targetAction = $('#myId').attr('data-action'); 

this gives a complete separation between .js and views. Of course, this requires a certain degree of planning.

Hope this helps

+3
source

The razor will be analyzed on the server side and replaced with the corresponding output. Therefore, in my opinion, it is completely indifferent if you put it in Javascript or HTML - only the output value will be visible on the client side. So in the above example, I would choose the first option (put it directly in JS), since you will not have an unnecessary hidden input field.

+2
source

I do not think there is a correct answer to this question; only pros and cons.

Pros of using Razor in Javascript

  • Script is tied to your view model; therefore, model changes will be received automatically and errors will be detected at compile time.

vs

  • Script mixes with markup, unlike the best web design methods (put the script at the bottom so that it never breaks your page).
  • Script cannot be compiled / reduced because, again, it mixes with your markup.
+1
source

All Articles