Razor syntax in JavaScript code block
asp.net-mvc-3, html, javascript, razor
Solution
I personally would go with an extension of the 2nd option and create a seperate .js file. The reason being, if you delegate work out to a 3rd party to take care of the jquery/javascript parts of the UI, then they need not have any sight of the backend functionality.
There are a variety of ways to use html5 attributes (i.e. data-attribute='foo') on the inputs which would allow you to 'decorate' your inputs with a cargo of properties which could be parsed inside the external .js file.
A very brief example:
in your view:
<input type='text' id='myId' data-action='@Url.Action("MyAction")' class='myClass' />
in your .js file:
var targetAction = $('#myId').attr('data-action');
this gives complete separation between the .js and the views. It does require a degree of planning of course.
Hope this helps
Problem
I want to know if it is a good practice to use razor in JavaScript code. For example: ``` <script type="text/javascript"> var variable = @some.Id </script> ``` Or it's better to create hidden value and then take it with JavaScript, like this? ``` <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> } ``` Is this good solution?