7

I'd like to use razor syntax inside my Javascript files. Is this possible without including the javascript inline into the page?

4
  • Why do you need to use Razor in your javascript files? What more specifically do you need to achieve? I bet there are better ways to achieve it. Commented Jan 26, 2012 at 10:27
  • possible duplicate of asp.net-mvc: razor '@' symbol in js file Commented Jan 26, 2012 at 10:29
  • @DarinDimitrov : I only really needed to use Url.Action() in my ajax requests. Commented Jan 26, 2012 at 12:30
  • @gdoron: I couldn't find that one when I was searching. I will add to your vote to close. Commented Jan 26, 2012 at 12:38

3 Answers 3

6

I found a razor engine RazorJS on nuget that solves @ in js files
The owner blog and explanations about the package abilities
The Nuget package

see more in this question

Sign up to request clarification or add additional context in comments.

Comments

3

The Razor engine only runs against the page, not any included javascript files.

You could write a custom parser that will run the view engine against any javascript files before serving them, and I imagine any attempt to do so would be a very useful open source project.

However, the simplest solution that comes to mind (if these variables are not sematically linked to any DOM elements) is to simply declare and initialise your variables in the page (or in an included partial page) and your javascript (in .js files) relies on these variables being defined.

If however the variables that you require are logically associated with DOM elements, I prefer to use data-* attributes to define these, this way your javascript can be consumed by the html, rather than the other way around. For example, if you have a content area that should be automatically updated by 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 ...
  });
});

1 Comment

+1 ...and alternatively you can pass the required values to your JS file in the querystring.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.