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

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


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.


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.


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.