asp.net-mvc: razor '@' symbol in js file

I have a .csHtml-razor file with a javascript function that uses the @Url.Content C# function inside for the ajax URL.
I want to move that function to a .js file referenced from my view.

The problem is that javascript doesn't "know" the @ symbol and doesn't parse the the C# code.
Is there a way to reference .js files from view with "@" symbol?


Solution 1:

You could use HTML5 data-* attributes. Let's suppose that you want to perform some action when some DOM element such as a div is clicked. So:

<div id="foo" data-url="@Url.Content("~/foobar")">Click me</div>

and then in your separate javascript file you could work unobtrusively with the DOM:

$('#foo').click(function() {
    var url = $(this).data('url');
    // do something with this url
});

This way you could have a pure separation between markup and script without you ever needing any server side tags in your javascript files.

Solution 2:

Well I've just found a razor engine on nuget that does it! Meaning solves @ syntax!
It's name is RazorJS.

The Nuget package


2016 Update:
The package wasn't updated for 5 years, and the project site link is dead. I do not recommend people to use this library anymore.

Solution 3:

One way to tackle the problem is:

Adding a partial view with the javascript functions to the view.
This way you can use the @ symbol and all your javascript functions are separated from the view.

Solution 4:

You have two options:

  • Use the value as a parameter in the function and wire-up in the view
  • Create a namespace (instead of public level variable which is considered bad practice in JS) and set this value at the top of the page and then use it in your js

For example:

 var MyCompany = 
 {
   MyProject: {
                  MyVariable:""
               }
  };

And then in your view, set it:

MyCompany.MyProject.MyVariable = @....

UPDATE

You might wonder none is any good because of coupling, well it is true, you are coupling js and view. That is why scripts must be oblivious to the location they are running in so it is a symptom of non-optimum organization of files.

Anyway there is a third option to create a view engine and run the js files against the razor and send the results back. This is cleaner but much slower so not recommended either.

Solution 5:

In order to get the @ variable into your .js file you'll have to use a global variable and set the value of that variable from the mvc view that is making use of that .js file.

JavaScript file:

var myValue;

function myFunc() {
  alert(myValue);
}

MVC View file:

<script language="text/javascript">
    myValue = @myValueFromModel;
</script>

Just be sure that any calls to your function happen AFTER the value has been set by the view.