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

gdoron is supporting Monica picture gdoron is supporting Monica · Oct 26, 2011 · Viewed 56k times · Source

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?

Answer

Darin Dimitrov picture Darin Dimitrov · Jan 9, 2012

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.