Can I use razor syntax in Javascript files?

I want to use razor syntax inside my Javascript files. Is this possible without including inline javascript in the page?

+7
source share
3 answers

I found a RazorJS razor RazorJS on nuget that solves @ to js files
Owner's blog and package features explanation
Nuget package

see more in this question

+6
source

The Razor engine only works with a page, not with javascript files.

You can write your own parser that will trigger the viewer against any javascript files before serving them, and I assume that any attempt to do this would be a very useful open source project.

However, the simplest solution that comes to mind (if these variables are not semantically related to any DOM elements) is to simply declare and initialize your variables on the page (or on the partial part with the part included) and your javascript (in .js ) depends on the definition of these variables.

If the variables you need are logically linked to DOM elements, I prefer to use the data-* attributes to data-* them, so your javascript can be used by html, and not vice versa. For example, if you have a content area that should be automatically updated using javascript (using jQuery as an example here):

HTML:

 <div data-auto-refresh="pathToContent" data-auto-refresh-milliseconds="1000"></div> 

JavaScript:

 $(function() { $('[data-auto-refresh]').each(function() { var self = $(this); var url = self.data('auto-refresh'); var interval = self.data('auto-refresh-milliseconds'); // Code to handle refresh here ... }); }); 
+3
source

You can set the value in a hidden field in yout cshtml file, and then in your javascript files you can access the hidden field.

+2
source

All Articles